I have the following program in 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();
}
The temporary files are created. However, there are two main problems with this program:
1) The temporary files are not discarded once the application terminates. 2) The file stream is not opening the file and is not writing any text.
How can these problems be solved please? Thanks :)
When you supply FILE_ATTRIBUTE_TEMPORARY
to Windows, is basically advisory -- it's telling the system that you intend to use this as a temporary file and delete it soon, so it should avoid writing data to disk if possible. It does not tell Windows to actually delete the file (at all). Perhaps you want FILE_FLAG_DELETE_ON_CLOSE
?
The problem with writing to the files appears pretty simple: you've specified 0
for the third parameter to CreateFile
. This basically means no file sharing, so as long as that handle to the file is open, nothing else can open that file. Since you never explicitly close the handles you created with CreateFile
, no other part of that program has an real possibility of writing to the file.
My advice would be to pick one type of I/O to use, and stick to it. Right now, you have a combination of Windows-native CreateFile
, C-style printf
and C++ style ofstream
. Frankly, it's a mess.