Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C to create a file and write+read to it, what went wrong?

Tags:

c

file-io

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
like image 906
user27314297 Avatar asked Dec 10 '25 15:12

user27314297


1 Answers

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, or rewind), 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
like image 174
dbush Avatar answered Dec 12 '25 05:12

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!