[英]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代码以来已经有一段时间了。 希望人们能通过大量问题的有用更正/通知来引起注意。 :)
这是一般过程
这是作业吗? 棘手的是,您必须跟踪字符串的长度以及使用/为空的字符串长度。 您可以猜测足够高的开头,或者在空间不足时调用malloc()
或其一个兄弟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.