在 C 中,我应该如何读取文本文件并打印所有字符串 [英] In C, how should I read a text file and print all strings

查看:19
本文介绍了在 C 中,我应该如何读取文本文件并打印所有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 test.txt

我想写一个 C 程序来读取这个文件并将内容打印到控制台(假设文件只包含 ASCII 文本).

I want to write a C program that can read this file and print the content to the console (assume the file contains only ASCII text).

我不知道如何获取我的字符串变量的大小.像这样:

I don't know how to get the size of my string variable. Like this:

char str[999];
FILE * file;
file = fopen( "test.txt" , "r");
if (file) {
    while (fscanf(file, "%s", str)!=EOF)
        printf("%s",str);
    fclose(file);
}

999 的大小不起作用,因为 fscanf 返回的字符串可能比它大.我该如何解决这个问题?

The size 999 doesn't work because the string returned by fscanf can be larger than that. How can I solve this?

推荐答案

最简单的方法是读取一个字符,读取后立即打印:

The simplest way is to read a character, and print it right after reading:

int c;
FILE *file;
file = fopen("test.txt", "r");
if (file) {
    while ((c = getc(file)) != EOF)
        putchar(c);
    fclose(file);
}

c 是上面的 int,因为 EOF 是一个负数,一个普通的 char 可能是 <代码>未签名.

c is int above, since EOF is a negative number, and a plain char may be unsigned.

如果你想分块读取文件,但没有动态内存分配,你可以这样做:

If you want to read the file in chunks, but without dynamic memory allocation, you can do:

#define CHUNK 1024 /* read 1024 bytes at a time */
char buf[CHUNK];
FILE *file;
size_t nread;

file = fopen("test.txt", "r");
if (file) {
    while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
        fwrite(buf, 1, nread, stdout);
    if (ferror(file)) {
        /* deal with error */
    }
    fclose(file);
}

上面的第二种方法本质上是你将如何使用动态分配的数组读取文件:

The second method above is essentially how you will read a file with a dynamically allocated array:

char *buf = malloc(chunk);

if (buf == NULL) {
    /* deal with malloc() failure */
}

/* otherwise do this.  Note 'chunk' instead of 'sizeof buf' */
while ((nread = fread(buf, 1, chunk, file)) > 0) {
    /* as above */
}

您使用 %s 作为格式的 fscanf() 方法会丢失有关文件中空格的信息,因此它并没有完全将文件复制到 stdout.

Your method of fscanf() with %s as format loses information about whitespace in the file, so it is not exactly copying a file to stdout.

这篇关于在 C 中,我应该如何读取文本文件并打印所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆