简体   繁体   English

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

[英]How to print all characters in this code in C on a linux terminal?

I want to read a file and print a line from that file. 我想读取一个文件并从该文件中打印一行。 Here is the code. 这是代码。

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

Here is the output as displayed from Ubuntu terminal. 这是从Ubuntu终端显示的输出。 输出图像

The first line in my movies.txt file is 1.Lord of the rings the fellowship of the ring , but only the last few characters are being printed out.So I need help to print out the entire line instead of just the last few characters. movies.txt文件中的第一行是1.Lord of the rings the fellowship of the ring ,但是只打印了最后几个字符。因此,我需要帮助来打印整个行,而不仅仅是最后几个字符。

Your program prints a line without a line terminator. 您的程序打印没有行终止符的行。 Apparently, your shell prompt contains code to return the cursor to the left margin before printing the prompt text; 显然,您的shell提示符包含用于在打印提示符文本之前将光标返回到左边距的代码。 and so, the prompt replaces part of the program's output. 因此,提示将替换程序输出的一部分。

With a simpler prompt, you would get something like 有了一个简单的提示,您将得到类似

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

where bash$ is your prompt. bash$是您的提示。

If this is not what you want, printf("%s\\n", ...) would be the normal and expected way to print a line with a newline added; 如果这不是您想要的,则printf("%s\\n", ...)将是打印添加了换行符的行的正常且预期的方式。 or, you could avoid trimming the newline in the first place. 或者,您可以避免首先修剪换行符。 If the program isn't one you can change yourself, adding a newline after running it could be done with 如果该程序不是您可以更改的程序,则可以在运行后添加换行符

bash$ ./new; echo

If you change your prompt to always print an empty line before the prompt text, you can avoid this problem altogether, but then you will typically want a rather big terminal window. 如果将提示更改为始终在提示文本之前打印空行,则可以完全避免此问题,但是通常情况下,您将需要一个较大的终端窗口。 (I see you already have one, but I guess that's just because you tolerate Ubuntu's insane default settings.) (我看到您已经有了一个,但是我想那是因为您可以忍受Ubuntu的疯狂默认设置。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM