【发布时间】:2012-10-27 16:42:22
【问题描述】:
我有以下 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) 文件流没有打开文件,也没有写入任何文本。
请问这些问题如何解决?谢谢:)
【问题讨论】:
-
"应用程序终止后临时文件不会被丢弃。" - 他们为什么要这样做?它们只是普通文件。关闭文件!= 删除它。
-
您在创建文件时是否尝试过使用 stl 而不是 win32 API?我认为在只写模式下打开一个文件,如果它还不存在的话就会创建它。
-
@H2CO3 "关闭文件!= 删除它。" - 注意
FILE_ATTRIBUTE_TEMPORARY。我猜 OP 认为该属性会导致所有关闭的文件被删除。 -
想法:不会泄露您使用裸 CreateFile() 调用创建的文件句柄。您报告它已成功创建,但不知道这是不是真的,因为您忽略了返回结果(即当前正在泄漏的打开的文件句柄)。
-
我会尝试将硬编码的文件名传递给 ofstream,以确保它不是字符串操作问题