How to Create a Temporary Text File in C++

How to create a temporary text file in C++?

Maybe this will help

FILE * tmpfile ( void );

http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/

Open a temporary file

Creates a temporary binary file, open
for update (wb+ mode -- see fopen for
details). The filename is guaranteed
to be different from any other
existing file. The temporary file
created is automatically deleted when
the stream is closed (fclose) or when
the program terminates normally.

See also

char * tmpnam ( char * str );

Generate temporary filename

A string containing a filename
different from any existing file is
generated. This string can be used to
create a temporary file without
overwriting any other existing file.

http://www.cplusplus.com/reference/clibrary/cstdio/tmpnam/

Reading through File with temp file in C

I think you want this:

while (fscanf(in, "%d %d\n", &A[in].from, &A[in].to) != EOF)
{
// empty block
}

or this:

do
{
fscanf(in, "%d %d\n", &A[in].from, &A[in].to);
}
while (!feof(in));

Your attempt of using temp instead of in for the getc is pointless as temp and in refer to the exact same FILE object.

Bonus hint

Another thing that is absolutely essential is checking if fopen fails:

FILE *in = fopen("sim_input.txt", "r");
if (in == NULL)
{
// take action if file could not be opened
}
else
{
// process file
}

In your code if the file does not exist or cannot be opened for whatever other reason you will fscan from a NULL FILE pointer which usually doesn't end well.

Create and open temporary text file with C# Winforms

You can do the following, using the clipboard and managing 'notepad.exe' process (it should work for any text editor):

1) Add this reference:

    [DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

2) Open notepad and paste your data:

public void OpenNotepad()
{
Clipboard.SetText("All your text");

Process process = Process.Start("notepad.exe");
process.WaitForInputIdle();
SetForegroundWindow(process.MainWindowHandle);
SendKeys.Send("^V");
}

Beware that this will not create any temporary file, but I assume that is the behavior you want.

What will be the best way to create a temporary text file for bash output processing and delete the file after the process ends

Continuing from the comment, in addition to creating the temporary file and setting a trap to remove the temp file on termination, interrupt or exit, you should validate each step along the way. You should validate mktemp provides a zero exit code. You should validate that the temp file is in fact created. Then you can use the temp file with confidence that no intervening error took place.

A short example would be:

#!/bin/bash

tmpfile=$(mktemp) ## create temporary file

[ "$?" -eq 0 ] || { ## validate zero exit code from mktemp
printf "error: mktemp had non-zero exit code.\n" >&2
exit 1
}

[ -f "$tmpfile" ] || { ## validate temp file actually created
printf "error: tempfile does not exist.\n" >&2
exit 1
}

## set trap to remove temp file on termination, interrupt or exit
trap 'rm -f "$tmpfile"' SIGTERM SIGINT EXIT

## Your Script Content Goes Here, below simply exercises the temp file as an example

## fill temp file with heredoc to test
cat > "$tmpfile" << eof
The temporary file was successfully create at: '$tmpfile'.
The temporary file will be removed by a trap function when this
script is terminated or interrupted, or when this script exits
normally.
eof

cat "$tmpfile" ## output temp file to terminal

There are several ways to approach this. This is just a plain-Jane, non-exiting way to put the pieces together and the validations to ensure it all happens as you intend.

Append a text to a beginning of a file in C does not work

since you're using a temporary file, a secondary buffer should not be required, just append the text, then move the old file contents into the new one.

A few things you should lookout for,

  • if (!fp1 && !fp2) is only true if both files failed to be opened ,its better to check the results individually so we know where we failed. You could have replaced && with || but it will be ambiguous why it failed unless you re-check the file pointer values.
  • It seems you were never writing the data from fp1 into fp2 I only see calls to fgets(), you read fp1 into buf then you read fp2 into buf, doing nothing with the data both times. If the files are larger than 100 bytes you'll end up with the last 100 or less bytes of data being stored in buf.
  • It's not necessarily the worst thing, but it is good practice to only open files with the permissions you require. opening a file you only need to read from in 'a+' mode is kind of odd
  • before creating new files its a good idea to check that a file doesn't already exist by that name. You might be better off to create the file in the system's temporary directory or a dedicated tmp dir for your program. Using a unique string for it's name is also a good idea. perhaps something like "[my prog]-[original file name]-[.tmp]" instead of such a general name.

A short example of a method that should work, with error checking (not necessarily the best error checking but gives you an idea where errors can occur):

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

int Prepend(char *string, char *file_name)
{
FILE *fp1 = NULL, *fp2 = NULL;
struct stat fs;
if (stat("temp_file", &fs) == 0) {
printf("Error, there is already a file named \"temp_file\" in the current working directory\n");
return -1;
}
if ((fp1 = fopen(file_name, "r")) == NULL) {
printf("Error : %s\n", strerror(errno));
printf("Failed to Open file %s\n", file_name);
return -1;
}
if ((fp2 = fopen("temp_file", "w")) == NULL {
printf("Error : %s\n", strerror(errno));
printf("Unable to create Temporary file\n");
fclose(fp1);
return -1;
}
if (fputs("Prepended String\n", fp2) == EOF) {
printf("Failed to write string to file\n");
fclose(fp1);
fclose(fp2);
if (remove("temp_file") != 0)
printf("Error : %s, while removing temp_file\n", strerror(errno));
return -1;
}
int c;
while((c = fgetc(fp1)) != EOF) {
if(fputc(c, fp2) == EOF) {
printf("Error while transfering data from %s to %s\n", file_name, "temp_file");
fclose(fp1);
fclose(fp2);
if (remove("temp_file") != 0)
printf("Error : %s, while removing temp_file\n", strerror(errno));

return -1;
}
}
fclose(fp1);
if (remove(file_name) != 0) {
printf("Error : %s, while removing %s\n", strerror(errno), file_name);
fclose(fp2);
return -1;
}

fclose(fp2);
if (rename("temp_file", file_name) != 0) {
printf("Error : %s, while renaming temp_file\n", strerror(errno));
return -1;
}
return 0;
}

fclose() can also return EOF on error and errno is set to indicate the error. However, any further access (including another call to fclose()) to the stream results in undefined behavior. so you can print the error but there isn't much you can do about it.



Related Topics



Leave a reply



Submit