我编写了一个程序来解决将指针写入文件 (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);
}
最佳答案
采取的步骤:
- 将数据写入文件。
- 关闭文件。
- 以读取模式再次打开文件。
- 从文件中读取数据。
这应该有效。
此外,输出文件名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/