C语言中,读取文本文件并打印其中的字符串有多种方法,具体取决于你的需求和文件的结构。在实际应用中,如果文件大小未知或可能很大,建议使用逐个字符读取的方法。如果文件大小可控且需要一次性处理所有字符,读取到缓冲区可能更方便。

1、逐字符读取并打印

最简单的方法,适用于打印整个文件内容。

#include <stdio.h>

int main() {
    FILE *file = fopen("test.txt", "r");
    if (file) {
        int c;
        while ((c = getc(file)) != EOF)
            putchar(c);
        fclose(file);
    } else {
        perror("Failed to open file");
    }
    return 0;
}

2、按行读取并打印

如希望逐行读取文件内容,可以使用 fgets

#include <stdio.h>

int main() {
    FILE *file = fopen("test.txt", "r");
    if (file) {
        char buffer[1024];
        while (fgets(buffer, sizeof(buffer), file))
            printf("%s", buffer);
        fclose(file);
    } else {
        perror("Failed to open file");
    }
    return 0;
}

3、读取整个文件到内存并打印

如需要将整个文件内容读取到一个字符串中,可以使用以下方法。

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

char* read_file(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (!file) return NULL;

    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    rewind(file);

    char *buffer = malloc(length + 1);
    if (!buffer) {
        fclose(file);
        return NULL;
    }

    fread(buffer, 1, length, file);
    buffer[length] = '\0';
    fclose(file);
    return buffer;
}

int main() {
    char *content = read_file("test.txt");
    if (content) {
        printf("%s", content);
        free(content);
    } else {
        perror("Failed to read file");
    }
    return 0;
}

4、按单词读取并打印

如希望逐个单词读取文件内容,可以使用 fscanf

#include <stdio.h>

int main() {
    FILE *file = fopen("test.txt", "r");
    if (file) {
        char word[100];
        while (fscanf(file, "%99s", word) == 1)
            printf("%s\n", word);
        fclose(file);
    } else {
        perror("Failed to open file");
    }
    return 0;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表