c - 使用指针写入/读取文件,C

标签 c file pointers 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);
}

最佳答案

采取的步骤:

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

关于c - 使用指针写入/读取文件,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388934/

相关文章:

c++ - 文件最后一行为空时的停止条件 C++

linux - 用 shell 脚本比较 2 个文件

c++ - 在 C++ 中确定指针限制的惯用方法是什么?

c - 当我使用 free() 释放分配的指针时出现无效指针错误

c - 什么是位掩码?

C 结构体数组默认值

java - 文本到二进制转换并写入文件。请帮助

c - 结构数组成员的指针转换问题

c - 用于棋盘游戏(国际象棋或其他)的灵活库或服务器?

c - S_ISDIR() 的问题导致 C(可能是因为 stat() 没有正确设置其结构?)