使用指针从文件写入 to/reading,C

Writing to/reading from file using pointers, C

我编写了一个程序来处理将指针写入文件 (fwrite) 和从文件读取指针 (fread)。然而,该程序似乎没有向文件中写入任何内容,也没有从文件中读取任何内容;它只是打印我的指针的最终增量 5 次并退出。谁能在我的语法中发现 error/mistake 似乎是这样做的?

#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);
}

撇开你不检查 fwrite() 的 return 值这一事实,我假设你在 运行 之后确实写入了 "test.c"程序文件应该以 5 * sizeof(int) 字节的大小存在。但是您无法读取它有两个原因:

  1. 您以只写方式打开文件。将 "wb" 更改为 "w+b" 以允许读取
  2. 写入后,必须重新设置读写指针到文件开头:读取前调用fseek(fTest, 0, SEEK_SET );

要采取的步骤:

  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);
}

问题是您在以写入模式打开文件时读取文件。

在你的写循环和读循环之间添加这段代码,它将起作用:

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