我正在嘗試編寫一個讀取所有TXT文件並將其複製到一個特定數組中的程序。但問題是空白字符。如果我使用fscanf,我無法將所有TXT文件放入一個數組中。如何將TXT文件複製到char數組中?從C中的TXT文件中讀取所有字符
0
A
回答
1
標準庫提供了在一次函數調用中能夠讀取文件的全部內容所需的所有功能。你必須首先確定文件的大小,確保分配足夠的內存來保存文件的內容,然後在一次函數調用中讀取所有內容。
#include <stdio.h>
#include <stdlib.h>
long getFileSize(FILE* fp)
{
long size = 0;
fpos_t pos;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
return size;
}
int main(int argc, char** argv)
{
long fileSize;
char* fileContents;
if (argc > 1)
{
char* file = argv[1];
FILE* fp = fopen(file, "r");
if (fp != NULL)
{
/* Determine the size of the file */
fileSize = getFileSize(fp);
/* Allocate memory for the contents */
fileContents = malloc(fileSize+1);
/* Read the contents */
fread(fileContents, 1, fileSize, fp);
/* fread does not automatically add a terminating NULL character.
You must add it yourself. */
fileContents[fileSize] = '\0';
/* Do something useful with the contents of the file */
printf("The contents of the file...\n%s", fileContents);
/* Release allocated memory */
free(fileContents);
fclose(fp);
}
}
}
1
你可以使用fread(3)
從這樣的流中讀取的一切:
char buf[1024];
while (fread(buf, 1, sizeof(buf), stream) > 0) {
/* put contents of buf to your array */
}
1
可以使用函數fgetc(<file pointer>)
返回從文件中讀取一個字符,如果你使用這個功能,你應該檢查讀字符是EOF
相關問題
- 1. 從C++中的txt文件中讀取字符
- 2. C++從.txt中讀取所有內容
- 3. 如何從txt文件中逐字符讀取字符並逐行讀取C++
- 4. C:讀取目錄中的所有* .txt文件
- 5. 讀取C:\\ Files \\中的所有.txt文件\\
- 6. 從Matlab中的txt文件中讀取
- 7. 從TXT文件中讀取所有行並僅在每行的每個FIRST字符串中搜索C#
- 8. 從java中的txt文件讀取比較字符串
- 9. 從C++讀取巨大的txt文件?
- 10. 閱讀從C++中的txt文件
- 11. 如何從txt文件中讀取特定數字C++
- 12. 如何從txt文件中正確讀取瑞典字符
- 13. 使用PHP從txt文件中讀取捷克字符
- 14. 從java中的.txt文件讀取
- 15. 麻煩從C++中的文件通過字符讀取字符
- 16. 在C#中讀取非txt文件
- 17. 在C程序中讀取文件.txt
- 18. 讀取文件中的Unicode字符C
- 19. C++讀取txt文件?
- 20. 讀取文件.txt C++
- 21. 用C++讀取.txt文件
- 22. 使用C++類從.txt文件讀取
- 23. C#:從txt文件讀取數據
- 24. 從txt文件讀取多行C++
- 25. 在.txt文件中逐字讀取到C++中的結構
- 26. 從C中的txt文件中讀取整數
- 27. 如何從C程序中讀取.txt文件或.csv文件?
- 28. Android:如何讀取包含中文字符的txt文件?
- 29. 如何從一個大的txt文件中僅有效地讀取字符串
- 30. 從文本文件中讀取文字C++(怪異字符)