Reputation: 541
I'm trying to create a couple of temporary files to write and read from, and then have destroyed when the program is complete. I have seen tmpfile
, which would be great, but I would like to know the name of that file as well. I've read the docs for ofstream
but I don't think I'm implementing things right. What I'm trying to do:
char xFile[64]
and char yFile[64]
.std::tmpnam(xFile); std::tmpnam(yFile)
. This assigns a c string like /y3s3
into xFile.On point #3, I wrote something like
void filemng::makeXCopy (std::string text) {
// actually I've tried fsteam and ifstream as well, shot in the dark
std::ofstream xfile(xFile, std::ofstream::out);
if(!xfile.good()) {
std::cerr << "Failed to open xFile.\n";
}
}
Of course, when I run it, I see "Failed to open xFile." I just cannot see what I'm doing wrong here.
Upvotes: 0
Views: 832
Reputation: 5387
Here is an example to do it using mkstemp:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char name[255] = "/tmp/mytempfile_XXXXXX";
int fd = mkstemp(name);
if (fd > 0) {
printf("Created %s\n", name);
write(fd, "some dataa\n", strlen("some dataa\n"));
close(fd);
} else {
printf("Failed \n");
}
return 0;
}
Note that "xxxxxx" in the string passed to mkstmp will be replaced with some unique string that will make the filename unique in the directory.
Upvotes: 1