我想将文件的数据读入字符串。
是否有将整个文件读入字符数组的函数? 我打开这样的文件:
FILE *fp;
for(i = 0; i < filesToRead; i++)
{
fp = fopen(name, "r");
// Read into a char array.
}
编辑:那么如何“逐行”读取它getchar()?
答案 0 :(得分:2)
以下是将整个文件读入连续缓冲区的三种方法:
计算文件长度,然后fread()
整个文件。您可以使用fseek()
和ftell()
计算长度,也可以在POSIX系统上使用fstat()
。这不适用于套接字或管道,它只适用于常规文件。
将文件读入缓冲区,在使用fread()
读取数据时动态扩展该缓冲区。典型的实现以“合理的”缓冲区大小开始,并在每次空间耗尽时加倍。这适用于任何类型的文件。
在POSIX上,使用fstat()
获取文件,然后使用mmap()
将整个文件放入地址空间。这仅适用于常规文件。
答案 1 :(得分:0)
您可以执行以下操作:
FILE *fp;
int currentBufferSize;
for(i = 0; i < filesToRead; i++)
{
fp = fopen(name, "r");
currentBufferSize = 0;
while(fp != EOF)
fgets(filestring[i], BUFFER_SIZE, fp);
}
当然,您必须以更强大的方式进行此操作,检查您的缓冲区是否可以保存所有数据等等...
答案 2 :(得分:0)
您可能会使用以下内容:在每行读取内容时,请仔细检查结果并将其传递给您选择的数据结构。我没有展示如何正确分配内存,但您可以预先malloc
并在必要时realloc
。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define FILE_BUFFER_SIZE 1024
int file_read_line(FILE *fp, char *buffer)
{
// Read the line to buffer
if (fgets(buffer, FILE_BUFFER_SIZE, fp) == NULL)
return -errno;
// Check for End of File
if (feof(fp))
return 0;
return 1;
}
void file_read(FILE *fp)
{
int read;
char buffer[FILE_BUFFER_SIZE];
while (1) {
// Clear buffer for next line
buffer[0] = '\0';
// Read the next line with the appropriate read function
read = file_read_line(fp, buffer);
// file_read_line() returns only negative numbers when an error ocurred
if (read < 0) {
print_fatal_error("failed to read line: %s (%u)\n",
strerror(errno), errno);
exit(EXIT_FAILURE);
}
// Pass the read line `buffer` to whatever you want
// End of File reached
if (read == 0)
break;
}
return;
}