繁体   English   中英

从文件读取多行到C中的字符串

[英]Read multiples lines from file to a string in C

如何从文本文件(可变宽度)读取多行并将所有行存储在C“字符串”中?

编辑:我想我会得到这些字符串并将它们存储在一个灵活的缓冲区中(通过realloc):)另外,即使看起来如此,这也不是功课(编程对我来说只是一种爱好)。 我只是出于好奇而问

由于这显然不是作业,因此下面是一些示例代码。 我只是为整个文件分配了一块巨大的内存,因为无论如何您最终都将要读取整个内容,但是如果要处理大文件,通常最好一次处理一行。

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

int main(int argc, char *argv[])
{
        // first, get the name of the file as an argument
        if (argc != 2) {
                printf("SYNTAX: %s <input file>\n", argv[0]);
                return -1;
        }

        // open the file
        FILE* fp = fopen(argv[1], "r");

        if (fp == NULL) {
                printf("ERROR: couldn't open file\n");
                return -2;
        }

        // seek to the end to get the length
        // you may want to do some error-checking here
        fseek(fp, 0, SEEK_END);
        long length = ftell(fp);

        // we need to seek back to the start so we can read from it
        fseek(fp, 0, SEEK_SET);

        // allocate a block of memory for this thing
        // the +1 is for the nul-terminator
        char* buffer = malloc((length + 1) * sizeof(char));

        if (buffer == NULL) {
                printf("ERROR: not enough memory to read file\n");
                return -3;
        }

        // now for the meat. read in the file chunk by chunk till we're done
        long offset = 0;
        while (!feof(fp) && offset < length) {
                printf("reading from offset %d...\n", offset);
                offset += fread(buffer + offset, sizeof(char), length-offset, fp);
        }

        // buffer now contains your file
        // but if we're going to print it, we should nul-terminate it
        buffer[offset] = '\0';
        printf("%s", buffer);

        // always close your file pointer
        fclose(fp);

        return 0;
}

ew,自从我编写C代码以来已经有一段时间了。 希望人们能通过大量问题的有用更正/通知来引起注意。 :)

这是一般过程

  1. 创建一个初始缓冲区。
  2. 从文件中读取一行,或者读取缓冲区中的剩余空间。
  3. EOF? 跳到6。
  4. 缓冲区已满? 重新分配更多空间。
  5. 冲洗并重复。
  6. 添加终止0

这是作业吗? 棘手的是,您必须跟踪字符串的长度以及使用/为空的字符串长度。 您可以猜测足够高的开头,或者在空间不足时调用malloc()或其一个兄弟。

您可以在此处尝试“可变长度”字符串实现:

如何在C中实现可变长度的'string'-y

然后,您必须将“ add”操作写入字符串。 然后,您可以安全地读取任何字节块,并将其连接到已经读取的字节上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM