2
我在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)文件流不打開文件,不寫任何文本。
請問這些問題怎麼解決?謝謝:)
」應用程序終止後,臨時文件不會被丟棄。「 - 他們爲什麼要這樣?他們只是普通的文件。關閉文件!=刪除它。 – 2012-11-07 15:35:48
您是否嘗試過使用stl而不是win32 API創建文件時?我認爲以只寫模式打開文件會創建它,如果它還不存在。 –
@ H2CO3「*關閉一個文件!=刪除它。*」 - 注意'FILE_ATTRIBUTE_TEMPORARY'。我猜測OP認爲該屬性會導致所有關閉的文件被刪除。 –