在C语言中,我应该怎么读取文本文件和打印的所有字符串 [英] In C, how should I read a text file and print all strings

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

问题描述

我有一个名为的文本文件的test.txt

I have a text file named 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 是一个负数,而一个普通的字符可能是无符号

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 */
}

您的方法的fscanf()%S 为格式文件中损失大约空白信息,因此它不正是将文件复制到标准输出

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天全站免登陆