David Tamrazov
David Tamrazov

Reputation: 597

Writing to/reading from file using pointers, C

I've written a program to mess around with writing pointers into files(fwrite) and reading into pointers from files(fread). However the program doesn't seem to write a single thing into the file, nor does it seem to read anything from the file; it just prints the final incrementation of my pointer 5 times and exits. Can anyone spot the error/mistake in my syntax that seems to be doing this?

#include <stdio.h>

int main() {
    FILE *fTest;
    int *testPtr;
    int x = 10;
    
    if ((fTest = fopen("test.c", "wb")) == NULL) {
        printf("Error!");
    }

    testPtr = &x;
    int i;
    for (i = 0; i < 5; i++) {
        fwrite(testPtr, sizeof(int), 1, fTest);
        *testPtr += 1;
    }
    
    for (i = 0; i < 5; i++) {
        fread(testPtr, sizeof(int), 1, fTest);
        printf("%d", *testPtr);
    }

    fclose(fTest);
}

Upvotes: 1

Views: 17148

Answers (3)

user5071535
user5071535

Reputation: 1412

The problem is that you're reading from the file while it's opened in write mode.

Add this code between your write loop and read loop and it will work:

fclose(fTest);
if ((fTest = fopen("test.c", "rb")) == NULL) {
    printf("Error!");
}

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

Steps to take:

  1. Write the data to the file.
  2. Close the file.
  3. Open the file again in read mode.
  4. Read the data from the file.

That should work.

Also, the output file name, test.c, seems a bit strange. Is that on purpose?

#include <stdio.h>

int main() {
    FILE *fTest;
    int *testPtr;
    int x = 10;
    char const* file = "test.data"; // Using .data instead of .c

    testPtr = &x;

    int i;

    // Write the data.
    if ((fTest = fopen(file, "wb")) == NULL) {
        printf("Error!");
    }
    for (i = 0; i < 5; i++) {
        fwrite(testPtr, sizeof(int), 1, fTest);
        *testPtr += 1;
    }

    fclose(fTest);

    // Read the data.
    if ((fTest = fopen(file, "rb")) == NULL) {
        printf("Error!");
    }

    for (i = 0; i < 5; i++) {
        fread(testPtr, sizeof(int), 1, fTest);
        printf("%d", *testPtr);
    }

    fclose(fTest);
}

Upvotes: 5

Ingo Leonhardt
Ingo Leonhardt

Reputation: 9894

Left aside the fact that you don't check thre return value of fwrite() I would assume that you do write into "test.c", after you run the program the file should exist with a size of 5 * sizeof(int) bytes. But you can't read from it for two reasons:

  1. you open the file write-only. Change "wb" to "w+b" to allow reading
  2. after writing, you must reset the read-write pointer to the beginning of the file: call fseek(fTest, 0, SEEK_SET ); before reading

Upvotes: 1

Related Questions