2012-11-07 81 views
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)文件流不打开文件,不写任何文本。

请问这些问题怎么解决?谢谢:)

+3

”应用程序终止后,临时文件不会被丢弃。“ - 他们为什么要这样?他们只是普通的文件。关闭文件!=删除它。 – 2012-11-07 15:35:48

+0

您是否尝试过使用stl而不是win32 API创建文件时?我认为以只写模式打开文件会创建它,如果它还不存在。 –

+0

@ H2CO3“*关闭一个文件!=删除它。*” - 注意'FILE_ATTRIBUTE_TEMPORARY'。我猜测OP认为该属性会导致所有关闭的文件被删除。 –

回答

3

当您提供FILE_ATTRIBUTE_TEMPORARY到Windows,基本上是咨询 - 它告诉你打算以此作为一个临时文件,并很快将其删除的系统,所以应该避免将数据写入到磁盘如果可能的话。它确实而不是告诉Windows实际上删除文件(完全)。也许你想FILE_FLAG_DELETE_ON_CLOSE

写入文件的问题看起来很简单:您已将第三个参数0指定为CreateFile。这基本上意味着没有文件共享,所以只要该文件的句柄是开放的,没有别的可以打开该文件。由于您从未明确关闭您使用CreateFile创建的句柄,因此该程序的其他部分没有真正写入文件的可能性。

我的建议是挑选一个类型的I/O使用,并坚持下去。现在,您可以使用Windows本机CreateFile,C风格printf和C++风格ofstream的组合。坦率地说,这是一团糟。 “