我想读取一个文件并打印该文件中的一行。这是代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* get_next_line(FILE* fpntr);
int main()
{
FILE* fp = fopen("movies.txt", "r");
char* tmp = get_next_line(fp);
printf("%s", tmp);
fclose(fp);
return 0;
}
char* get_next_line(FILE* fpntr)
{
char buff[2048];
int index = 0;
int ch = fgetc(fpntr);
while(ch != '\n' && ch != EOF)
{
buff[index++] = ch;
ch = fgetc(fpntr);
}
buff[index] = '\0';
char* tmp;
tmp = (char*)malloc((int)(index)*sizeof(char));
strcpy(tmp,buff);
return tmp;
}
我的 movies.txt
文件的第一行是 1.Lord of the rings the fellowship of the ring
,但只打印了最后几个字符。所以我需要帮助来打印出整行,而不仅仅是最后几个字符。
最佳答案
您的程序打印一行没有行终止符。显然,您的 shell 提示包含在打印提示文本之前将光标返回到左边距的代码;因此,提示替换了部分程序输出。
使用更简单的提示,你会得到类似的东西
bash$ ./new
1. Lord of the rings the fellowship of the ringbash$
bash$
是您的提示。
如果这不是您想要的,printf("%s\n", ...)
将是打印一行并添加换行符的正常且预期的方式;或者,您可以避免首先修剪换行符。如果该程序不是您可以自己更改的程序,则可以在运行后添加一个换行符
bash$ ./new; echo
如果您将提示更改为始终在提示文本之前打印一个空行,则可以完全避免此问题,但您通常需要一个相当大的终端窗口。 (我看到你已经有了一个,但我猜那只是因为你容忍了 Ubuntu 疯狂的默认设置。)
关于c - 如何在 linux 终端上用 C 打印这段代码中的所有字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35980516/