使用指针C写入文件/从文件读取

Dav*_*zov 0 c pointers file fwrite fread

我编写了一个程序,将指针写入文件(fwrite)并从文件读取指针(fread)。但是,该程序似乎没有在文件中写入任何内容,也没有从文件中读取任何内容。它只是将指针的最终增量打印5次并退出。谁能在我的语法中发现似乎正在执行此操作的错误/错误?

#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);
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 5

采取的步骤:

  1. 将数据写入文件。
  2. 关闭文件。
  3. 在读取模式下再次打开文件。
  4. 从文件中读取数据。

那应该工作。

另外,输出文件名test.c似乎有点奇怪。那是故意的吗?

#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);
}
Run Code Online (Sandbox Code Playgroud)