![](/img/trans.png)
[英]C program to print given number of lines from beginning of text file. File name and number of lines from command line argument
[英]C program to read a text file line by line then print out those lines to the terminal
我想让ac程序逐行读取文本文件,然后将这些行打印到终端。
我的密码
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char* line;
FILE *ifp;
ifp = fopen("BBE.txt", "r");
if (ifp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
while (fscanf(ifp, "%s", line) == 1)
{
printf("%s\n", line);
}
fclose(ifp);
return 0;
}
该程序在我尝试运行时不会将任何内容打印到终端。 这告诉我,while循环不起作用,但是我不确定为什么。
您的循环无法正常工作,因为fscanf
不会在成功返回仅返回1
。
根据fscanf
的手册页,返回值具有以下含义:
返回值
成功后,这些函数将返回成功匹配和分配的输入项的数量; 如果较早匹配失败,则该值可以小于所提供的值,甚至为零。
如果在第一次成功转换或匹配失败发生之前到达输入结束,则返回EOF值。 如果发生读取错误,也会返回EOF,在这种情况下,将设置流的错误指示符(请参见ferror(3)),并设置errno来指示错误。
此外,如另一个答案中所述:您写入的内存不是您的内存:
char* line;
只是一个char指针的声明。 您需要的是要写入的连续char数组。
您可以通过声明它在堆栈上分配它:
char line[1000]; // Allocate a char array of the size of 1000.
或堆上;
char* line = malloc(1000*sizeof(char)); // Allocate 1000 chars on the heap
在这里你必须释放内存
free(line);
您使用*line
而不初始化它->未定义行为。
要解决此问题,可以改用char数组:
char line[1000] = "";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.