如何在 linux 终端上用 C 语言打印此代码中的所有字符?
How to print all characters in this code in C on a linux terminal?
我想读取一个文件并打印该文件中的一行。这是代码。
#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] = '[=11=]';
char* tmp;
tmp = (char*)malloc((int)(index)*sizeof(char));
strcpy(tmp,buff);
return tmp;
}
这是 Ubuntu 终端显示的输出。
我的 movies.txt
文件中的第一行是 1.Lord of the rings the fellowship of the ring
,但只打印了最后几个字符 out.So 我需要帮助来打印整行,而不仅仅是最后几个字符。
您的程序打印出一行没有行终止符。显然,您的 shell 提示包含在打印提示文本之前 return 将光标移至左边距的代码;因此,提示替换了部分程序输出。
使用更简单的提示,您会得到类似
的内容
bash$ ./new
1. Lord of the rings the fellowship of the ringbash$
其中 bash$
是您的提示。
如果这不是您想要的,printf("%s\n", ...)
将是打印添加了换行符的行的正常且预期的方式;或者,您可以避免首先修剪换行符。如果程序不是你可以自己改变的,在 运行 之后添加一个换行符可以用
完成
bash$ ./new; echo
如果您将提示更改为始终在提示文本之前打印一个空行,则可以完全避免此问题,但是您通常需要一个相当大的终端 window。 (我看到你已经有了一个,但我想那只是因为你容忍了 Ubuntu 疯狂的默认设置。)
我想读取一个文件并打印该文件中的一行。这是代码。
#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] = '[=11=]';
char* tmp;
tmp = (char*)malloc((int)(index)*sizeof(char));
strcpy(tmp,buff);
return tmp;
}
这是 Ubuntu 终端显示的输出。
我的 movies.txt
文件中的第一行是 1.Lord of the rings the fellowship of the ring
,但只打印了最后几个字符 out.So 我需要帮助来打印整行,而不仅仅是最后几个字符。
您的程序打印出一行没有行终止符。显然,您的 shell 提示包含在打印提示文本之前 return 将光标移至左边距的代码;因此,提示替换了部分程序输出。
使用更简单的提示,您会得到类似
的内容bash$ ./new
1. Lord of the rings the fellowship of the ringbash$
其中 bash$
是您的提示。
如果这不是您想要的,printf("%s\n", ...)
将是打印添加了换行符的行的正常且预期的方式;或者,您可以避免首先修剪换行符。如果程序不是你可以自己改变的,在 运行 之后添加一个换行符可以用
bash$ ./new; echo
如果您将提示更改为始终在提示文本之前打印一个空行,则可以完全避免此问题,但是您通常需要一个相当大的终端 window。 (我看到你已经有了一个,但我想那只是因为你容忍了 Ubuntu 疯狂的默认设置。)