I have this C code that I am trying to use to create a file, write any arbitrary text from it, and then just print that out. When I run this the output is... less than expected. I've tried about everything I know of, and I think of myself as a pretty advanced C programmer, without any experience of file streams. Without further ado, have fun with this:
// This code is purely for testing and practicing the mechanics
// of file I/O
#include <stdio.h>
#define SIZE 256
int main() {
FILE *fptr = fopen("mem.txt","w+"); // Override/create a two-way file stream
char buffer[SIZE + 1]; // Also hold a null char
buffer[SIZE] = '\0';
if(!fptr) { // fptr will be null if not successful
printf("Failed creation");
return -1; // oof no file
}
printf("Creation successful\n");
fprintf(fptr, "Hello, World!"); // Write to fptr
fread(buffer, sizeof(buffer), 1, fptr); // Read immediately afterwards
printf("%s", buffer);
fclose(fptr);
return 0;
}
The expected output:
Creation successful
Hello, World!
vs. what I got
Creation successful
After you write the string to the file, you're immediately performing a read. Such an operation is not allowed without first resetting the file's current position.
This is detailed in section 7.23.5.3p7 of the C standard regarding the fopen
function:
However, output shall not be directly followed by input without an intervening call to the
fflush
function or to a file positioning function (fseek
,fsetpos
, orrewind
), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file
You first need to reset the current position to the start of the file, which you can do with the rewind
function.
fprintf(fptr, "Hello, World!"); // write to fptr
rewind(fptr);
fread(buffer, sizeof(buffer), 1, fptr); // read immediately afterwards