简体   繁体   English

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

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

How can I read multiple lines from a text file (variable width) and store all of them in a C "string"? 如何从文本文件(可变宽度)读取多行并将所有行存储在C“字符串”中?

EDIT: I guess I'll be fget'ing the strings and storing them in one flexible buffer (via realloc) :) Also, this is not homework even though it apparently seems so (programming is just a hobby for me). 编辑:我想我会得到这些字符串并将它们存储在一个灵活的缓冲区中(通过realloc):)另外,即使看起来如此,这也不是功课(编程对我来说只是一种爱好)。 I was just asking out of curiosity 我只是出于好奇而问

Since this apparently isn't homework, here's some sample code of how I'd do it. 由于这显然不是作业,因此下面是一些示例代码。 I'm just allocating a huge block of memory for the entire file, since you're going to read the whole thing eventually anyway, but if you're dealing with large files it's usually better to handle them a line at a time. 我只是为整个文件分配了一块巨大的内存,因为无论如何您最终都将要读取整个内容,但是如果要处理大文件,通常最好一次处理一行。

#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;
}

Whew, it's been a while since I've written C code. ew,自从我编写C代码以来已经有一段时间了。 Hopefully people will chime in with helpful corrections/notices of massive problems. 希望人们能通过大量问题的有用更正/通知来引起注意。 :) :)

Here's the general process 这是一般过程

  1. Create an initial buffer. 创建一个初始缓冲区。
  2. Read a line from the file, or up to the remaining space in the buffer. 从文件中读取一行,或者读取缓冲区中的剩余空间。
  3. EOF? EOF? Skip to 6. 跳到6。
  4. Filled the buffer? 缓冲区已满? Reallocate with more space. 重新分配更多空间。
  5. Rinse and repeat. 冲洗并重复。
  6. Add a terminating 0 添加终止0

Is this homework? 这是作业吗? The tricky thing here is that you must keep track of the string length and how much of it is used/empty. 棘手的是,您必须跟踪字符串的长度以及使用/为空的字符串长度。 Either guess high enough to begin with, or call malloc() or one of its brothers when you are out of space. 您可以猜测足够高的开头,或者在空间不足时调用malloc()或其一个兄弟。

You can try the "variable length" string implementation here: 您可以在此处尝试“可变长度”字符串实现:

How to implement a variable-length 'string'-y in C 如何在C中实现可变长度的'string'-y

And then, you'll have to write the "add" operation to the string. 然后,您必须将“ add”操作写入字符串。 Then, you can safely read any chunk of bytes, and concatenate it to what you have already read. 然后,您可以安全地读取任何字节块,并将其连接到已经读取的字节上。

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

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