J'ai le programme suivant en C++:écriture dans un fichier temporaire
#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();
}
Les fichiers temporaires sont créés. Cependant, il y a deux problèmes principaux avec ce programme:
1) Les fichiers temporaires ne sont pas mis au rebut une fois que l'application se termine. 2) Le flux de fichier n'ouvre pas le fichier et n'écrit aucun texte.
Comment peut-on résoudre ces problèmes s'il vous plaît? Merci :)
« Les fichiers temporaires ne sont pas mis au rebut une fois que l'application se termine. » - Pourquoi devraient-ils? Ce sont juste des fichiers normaux. Fermer un fichier! = Le supprimer. –
Avez-vous essayé d'utiliser stl au lieu de l'API win32 Lors de la création d'un fichier? Je pense que l'ouverture d'un fichier en mode écriture seule le crée s'il n'existe pas encore. –
@ H2CO3 "* Fermer un fichier! = Le supprimer. *" - Notez le 'FILE_ATTRIBUTE_TEMPORARY'. Je suppose que l'OP pense que cet attribut entraîne la suppression de tous les fichiers fermés. –