Hello,

I am trying to use temporary files in my C program but I am getting a Debug Assertion Failed error.
It happens when the program terminates. I am using ANSI C functions.

I am posting test code below. I have taken out all error checks for clarity.

#include <stdlib.h>
#include <stdio.h>

int main()
{
FILE * tempFile;
FILE * fp;
char string[80] = {0};
long length = 0;

fp = fopen("test.txt", "r");

fseek(fp, 0l, SEEK_END);
length = ftell(fp); /*get length of file*/
fseek(fp, 0l, SEEK_SET);

tempFile = tmpfile();

fread((void *)tempFile, sizeof(char), length, fp); /*copy file to tempfile, this is the problem*/

printf("%s\n", tempFile); /*prints out whole file*/

fseek(fp, 0l, SEEK_SET);

fgets(string, 80, fp);
printf("%s\n", string);

fseek(tempFile, 0l, SEEK_SET); /*fseek returns a -1 here meaning it can't seek*/

fgets(string, 80, tempFile);
printf("%s\n", string);

fclose(fp);
fclose(tempFile);

return 0;
}

I know why the error happens, it is becuase of the fread, probably tring to free memory that isn't there,
but how else do I copy the whole file? Am I using tmpfile wrong? If so can you please direct me to the correct
way to use tmpfile.

The reason I want to do this is for file safety, I don not want the file to get corrupted if the OS crashes.
Open file, copy to buffer, close file, use buffer to parse and format data instead of the file.
Any help is very much appreciated.

Thank you,
UC.