如何在Linux终端上用C打印此代码中的所有字符?

时间:2016-03-14 06:03:47

标签: c linux terminal fgets

我想读取一个文件并从该文件中打印一行。这是代码。

#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;
}

这是Ubuntu终端显示的输出。 Output Image

我的movies.txt文件中的第一行是1.Lord of the rings the fellowship of the ring,但只打印出最后几个字符。所以我需要帮助打印整行而不是最后几个字符。

1 个答案:

答案 0 :(得分:1)

您的程序打印一行没有行终止符。显然,shell提示符包含在打印提示文本之前将光标返回到左边距的代码;因此,提示替换了程序输出的一部分。

通过更简单的提示,您可以获得类似

的内容
bash$ ./new
1. Lord of the rings the fellowship of the ringbash$

其中bash$是您的提示。

如果这不是您想要的,printf("%s\n", ...)将是添加换行符的正常和预期的打印方式;或者,您可以避免首先修剪换行符。如果程序不是您自己可以更改的程序,则可以在运行后添加换行符

bash$ ./new; echo

如果您将提示更改为始终在提示文本之前打印空行,则可以完全避免此问题,但是您通常需要一个相当大的终端窗口。 (我看你已经有了一个,但我猜这只是因为你容忍Ubuntu疯狂的默认设置。)