从文本文件读取所有内容-C [英] Reading all content from a text file - C

查看:494
本文介绍了从文本文件读取所有内容-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文本文件中读取所有内容。这是我编写的代码。

I am trying to read all content from a text file. Here is the code which I wrote.

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

#define PAGE_SIZE 1024

static char *readcontent(const char *filename)
{
    char *fcontent = NULL, c;
    int index = 0, pagenum = 1;
    FILE *fp;
    fp = fopen(filename, "r");

    if(fp) {
        while((c = getc(fp)) != EOF) {
            if(!fcontent || index == PAGE_SIZE) {
                fcontent = (char*) realloc(fcontent, PAGE_SIZE * pagenum + 1);
                ++pagenum;
            }
            fcontent[index++] = c;
        }
        fcontent[index] = '\0';
        fclose(fp);
    }
    return fcontent;
}

static void freecontent(char *content)
{
    if(content) {
        free(content);
        content = NULL;
    }
}

这是用法

int main(int argc, char **argv)
{
    char *content;
    content = readcontent("filename.txt");
    printf("File content : %s\n", content);
    fflush(stdout);
    freecontent(content);
    return 0;
}

由于我是C语言新手,所以我想知道这段代码是否完美?您是否看到任何问题/改进?

Since I am new to C, I wonder whether this code looks perfect? Do you see any problems/improvements?

使用的编译器:GCC。但是该代码有望跨平台。

Compiler used : GCC. But this code is expected to be cross platform.

任何帮助将不胜感激。

Any help would be appreciated.

编辑

此处是带有的更新代码fread ftell

static char *readcontent(const char *filename)
{
    char *fcontent = NULL;
    int fsize = 0;
    FILE *fp;

    fp = fopen(filename, "r");
    if(fp) {
        fseek(fp, 0, SEEK_END);
        fsize = ftell(fp);
        rewind(fp);

        fcontent = (char*) malloc(sizeof(char) * fsize);
        fread(fcontent, 1, fsize, fp);

        fclose(fp);
    }
    return fcontent;
}

我想知道此功能的相对复杂性是什么?

I am wondering what will be the relative complexity of this function?

推荐答案

您应尝试查看函数 fsize 关于fsize,请参见下面的更新)和 fread

You should try look into the functions fsize (About fsize, see update below) and fread. This could be a huge performance improvement.

使用 fsize 来获取正在读取的文件的大小。使用此大小仅分配一个内存。 (关于fsize,请参见下面的更新。获取文件大小并执行一次分配的想法仍然相同)。

Use fsize to get the size of the file you are reading. Use this size to do one alloc of memory only. (About fsize, see update below. The idea of getting the size of the file and doing one alloc is still the same).

使用 fread 来阻止文件读取。这比单字符读取文件快得多。

Use fread to do block reading of the file. This is much faster than single charecter reading of the file.

类似这样的事情:

long size = fsize(fp);
fcontent = malloc(size);
fread(fcontent, 1, size, fp);

更新

不确定fsize是否跨平台,但是您可以使用此方法获取文件的大小:

Not sure that fsize is cross platform but you can use this method to get the size of the file:

fseek(fp, 0, SEEK_END); 
size = ftell(fp);
fseek(fp, 0, SEEK_SET); 

这篇关于从文本文件读取所有内容-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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