我在 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();
}
临时文件被创建。但是,这个程序有两个主要问题:
1)一旦应用程序终止,临时文件不会被丢弃。2)文件流没有打开文件,也没有写入任何文本。
请问这些问题怎么解决?谢谢 :)