我想要的文件的數據讀入一個字符串。讀取文件作爲字符串
是否有將整個文件讀入字符數組的函數? 我打開這樣的文件:
FILE *fp;
for(i = 0; i < filesToRead; i++)
{
fp = fopen(name, "r");
// Read into a char array.
}
編輯:那麼如何讀它「逐行」的getchar()?
我想要的文件的數據讀入一個字符串。讀取文件作爲字符串
是否有將整個文件讀入字符數組的函數? 我打開這樣的文件:
FILE *fp;
for(i = 0; i < filesToRead; i++)
{
fp = fopen(name, "r");
// Read into a char array.
}
編輯:那麼如何讀它「逐行」的getchar()?
這裏有三種方法來讀取整個文件到一個連續的緩衝區:
圖出來的文件長度,然後fread()
整個文件。你可以用fseek()
和ftell()
來計算長度,或者你可以在POSIX系統上使用fstat()
。這不適用於套接字或管道,它只適用於常規文件。
將文件讀入緩衝區,當您使用fread()
讀取數據時,該緩衝區會動態擴展。典型的實現以「合理的」緩衝區大小開始,每當空間耗盡時加倍。這適用於任何類型的文件。
在POSIX上,使用fstat()
獲取文件,然後使用mmap()
將整個文件放入地址空間。這隻適用於普通文件。
是的,我打算使用FSTAT()讀取之前分配數組大小。但是,實際從文件中獲取數據對我來說是個謎。 –
@MikeJohn:是的,使用'FREAD()'。見上面的#1。 –
@Mike約翰這是_the_方式來讀取整個文件。可能有文件嵌入'\ 0'字節,所以考慮到,如果你想使用「字符串」,這是'\ 0'終止。還要考慮以二進制打開文件:「rb」。 – chux
你可以做到以下幾點:
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);
}
當然,你將不得不作出這個更可靠的方法,檢查如果你的緩衝區可以容納所有的數據等等...
您可能會使用類似下面的內容:在每行讀取的地方,仔細檢查結果並將其傳遞給您選擇的數據結構。我還沒有表現出如何正確分配內存,但你可以在必要時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;
}
斑點,固定 – Pankrates
除非你寫一個。您必須按行 – Pankrates
讀取每個文件行,當然,[memmap](http://pubs.opengroup.org/onlinepubs/009695399/functions/mmap.html)文件,然後您可以以數組的形式訪問它。 –
如何逐行閱讀?或者你的意思是char by char? –