c語(yǔ)言怎么將文件內(nèi)容倒序輸出

小億
106
2024-05-13 18:15:19

以下是一個(gè)C語(yǔ)言程序,可以將文件內(nèi)容按行倒序輸出:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *file;
    file = fopen("input.txt", "r"); // 打開要讀取的文件

    if (file == NULL) {
        printf("無(wú)法打開文件\n");
        exit(1);
    }

    char lines[100][100]; // 假設(shè)每行最多包含100個(gè)字符

    int count = 0;
    while (fgets(lines[count], 100, file)) {
        count++;
    }

    for (int i = count - 1; i >= 0; i--) {
        printf("%s", lines[i]); // 逐行倒序輸出內(nèi)容
    }

    fclose(file); // 關(guān)閉文件

    return 0;
}

請(qǐng)將上述代碼保存為reverse.c文件,同時(shí)在同一目錄下創(chuàng)建一個(gè)名為input.txt的文本文件,里面寫入需要倒序輸出的內(nèi)容。然后使用C編譯器編譯并運(yùn)行該程序,即可看到文件內(nèi)容以倒序方式輸出。

0