【发布时间】:2021-12-30 21:28:21
【问题描述】:
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//opening collection.txt using ptr
FILE *ptr;
char data[1000];
ptr = fopen("collection.txt", "r");
printf("Hello world \n");
fscanf(ptr, "%s", data);
printf("%s \n", data);
fclose(ptr);
return 0;
}
collection.txt:
hi my name is
当我运行这个程序时,我得到:
Hello world
P7k
P7k 是我假设的内存位置。
我查看了多个网站和文章,但无法弄清楚如何打印 collection.txt 中的文本
【问题讨论】:
-
添加检查
fopen是否成功:if (ptr == NULL) { printf("Could not open file\n"); return 1; }另外总是检查所有scanf的功能(如fscanf)returns。 -
@Someprogrammerdude 使用了 if 条件,但没有运气:(检查了 fscanf 的返回值,但没有多大帮助
-
fopen是否成功,ptr在fopen调用后不是空指针?而fscanf返回1? -
@Someprogrammerdude 是的,我确实做到了,但不是运气。是的 fscanf 返回 1
-
还将
fscanf(ptr, "%s", data);替换为fgets(data, sizeof(data), ptr);看看会发生什么。