2012-11-07 80 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的組合。坦率地說,這是一團糟。 「