gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:41:42 24 4
gpt4 key购买 nike

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

编辑:我想我会 fget'ing 字符串并将它们存储在一个灵活的缓冲区中(通过 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;
}

哇,自从我编写 C 代码以来已经有一段时间了。希望人们会提出有用的更正/大量问题的通知。 :)

关于c - 从文件中读取多行到 C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3233645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com