写入临时文件

问题描述 投票:0回答: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) 文件流没有打开文件,也没有写入任何文本。

请问这些问题如何解决? 谢谢:)

c++ file text stream
2个回答
3
投票

当您向 Windows 提供

FILE_ATTRIBUTE_TEMPORARY
时,基本上是建议性的 - 它告诉系统您打算将其用作临时文件并尽快删除它,因此如果可能的话,应该避免将数据写入磁盘。它“不会”告诉 Windows 实际删除该文件(根本)。也许你想要FILE_FLAG_DELETE_ON_CLOSE
写入文件的问题看起来非常简单:您已将第三个参数指定为 

0

。这基本上意味着没有文件共享,因此只要文件的句柄打开,其他任何东西都无法打开该文件。由于您从未显式关闭使用

CreateFile
创建的句柄,因此该程序的其他部分都不可能真正写入该文件。
我的建议是选择
一个
类型的 I/O 来使用,并坚持使用。现在,您拥有 Windows 原生

CreateFile

、C 风格 CreateFile 和 C++ 风格

printf
的组合。老实说,这很乱。
    
如果您想在应用程序关闭后立即删除该文件,请使用


0
投票

。它是安全的,您可以每个进程打开几千个文件(参见

std::tmpfile()
值)并且与平台无关。
以下代码将创建一个空文件,并在关闭后立即将其删除。
TMP_MAX

注意如果你的程序异常退出,文件是否被删除是由实现定义的。

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.