2014-03-19 51 views
0

我正在嘗試編寫一個讀取所有TXT文件並將其複製到一個特定數組中的程序。但問題是空白字符。如果我使用fscanf,我無法將所有TXT文件放入一個數組中。如何將TXT文件複製到char數組中?從C中的TXT文件中讀取所有字符

回答

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