簡體   English   中英

如何在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] = '\0';
    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 ,但是只打印了最后幾個字符。因此,我需要幫助來打印整個行,而不僅僅是最后幾個字符。

您的程序打印沒有行終止符的行。 顯然,您的shell提示符包含用於在打印提示符文本之前將光標返回到左邊距的代碼。 因此,提示將替換程序輸出的一部分。

有了一個簡單的提示,您將得到類似

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

bash$是您的提示。

如果這不是您想要的,則printf("%s\\n", ...)將是打印添加了換行符的行的正常且預期的方式。 或者,您可以避免首先修剪換行符。 如果該程序不是您可以更改的程序,則可以在運行后添加換行符

bash$ ./new; echo

如果將提示更改為始終在提示文本之前打印空行,則可以完全避免此問題,但是通常情況下,您將需要一個較大的終端窗口。 (我看到您已經有了一個,但是我想那是因為您可以忍受Ubuntu的瘋狂默認設置。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM