C++ 写入临时文件

C++ 写入临时文件,c++,file,text,stream,C++,File,Text,Stream,我有以下C++程序: #include "stdafx.h" #include <fstream> #include <iostream> #include <sstream> #include <string> #include <string.h> #include <Windows.h> using namespace std; string integer_conversion(int num) //Method

我有以下C++程序:

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <string.h>
#include <Windows.h>

using namespace std;

string integer_conversion(int num) //Method to convert an integer to a string
{
    ostringstream stream;
    stream << num;
    return stream.str();
}

void main()
{
    string path = "C:/Log_Files/";
    string file_name = "Temp_File_";
    string extension = ".txt";
    string full_path;
    string converted_integer;
    LPCWSTR converted_path;

    printf("----Creating Temporary Files----\n\n");
    printf("In this program, we are going to create five temporary files and store some text in them\n\n");

    for(int i = 1; i < 6; i++)
    {
        converted_integer = integer_conversion(i); //Converting the index to a string
        full_path = path + file_name + converted_integer + extension; //Concatenating the contents of four variables to create a temporary filename

        wstring temporary_string = wstring(full_path.begin(), full_path.end()); //Converting the contents of the variable 'full_path' from string to wstring
        converted_path = temporary_string.c_str(); //Converting the contents of the variable 'temporary_string' from wstring to LPCWSTR

        cout << "Creating file named: " << (file_name + converted_integer + extension) << "\n";
        CreateFile(converted_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL); //Creating a temporary file
        printf("File created successfully!\n\n");

        ofstream out(converted_path);

        if(!out)
        {
            printf("The file cannot be opened!\n\n");
        }
        else
        {
            out << "This is a temporary text file!"; //Writing to the file using file streams
            out.close();
        }
    }
    printf("Press enter to exit the program");
    getchar();
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
string integer\u conversion(int num)//将整数转换为字符串的方法
{
ostringstream;

stream当您向Windows提供
文件\u属性\u临时文件时,它基本上是建议性的——它告诉系统您打算将其作为临时文件使用,并很快将其删除,因此如果可能,它应该避免将数据写入磁盘。它不告诉Windows实际删除该文件(根本不)。也许您希望关闭时
文件\u标记\u删除\u

写入文件的问题似乎很简单:您已经为
CreateFile
的第三个参数指定了
0
。这基本上意味着没有文件共享,因此只要文件的句柄打开,其他任何东西都无法打开该文件。因为您从未显式关闭使用
CreateFile创建的句柄e> ,该程序的任何其他部分都不可能写入该文件


我建议您选择一种类型的I/O来使用,并坚持下去。现在,Windows本地代码“Cyto> CeaFeFiels,C风格>代码> Prtff和C++风格>代码> OfStase。坦率地说,这是一个混乱。

“应用程序终止后,暂时文件不会被丢弃。”-为什么要这样做?它们只是普通文件。关闭文件!=删除文件。您在创建文件时是否尝试过使用stl而不是win32 API?我认为,在仅写模式下打开文件会在文件不存在时创建它。@H2CO3“关闭文件!=删除文件。”-请注意
文件属性\u TEMPORARY
。我猜OP认为该属性会导致删除所有已关闭的文件。想法:不泄漏通过裸CreateFile()调用创建的文件句柄。您报告它已成功创建,但由于忽略返回结果,因此不知道这是否为真(即,一个打开的文件句柄当前正在泄漏)。我将尝试将一个硬编码文件名传递给ofstream,以确保它不是字符串操作问题