2010-06-04 79 views
3

我從一個文件reaing,當我讀,它通過線需要它線,並打印出來從文件字符數組閱讀

是我想要的字符持有所有字符數組正是我想要的在該文件,並打印一次,

這是代碼我有

if(strcmp(str[0],"@")==0) 
     { 
      FILE *filecomand; 
      //char fname[40]; 
      char line[100]; 
      int lcount; 
      ///* Read in the filename */ 
      //printf("Enter the name of a ascii file: "); 
      //fgets(History.txt, sizeof(fname), stdin); 

      /* Open the file. If NULL is returned there was an error */ 
      if((filecomand = fopen(str[1], "r")) == NULL) 
      { 
        printf("Error Opening File.\n"); 
        //exit(1); 
      } 
      lcount=0; 
      int i=0; 
      while(fgets(line, sizeof(line), filecomand) != NULL) { 
       /* Get each line from the infile */ 
        //lcount++; 
        /* print the line number and data */ 
        //printf("%s", line); 

      } 

      fclose(filecomand); /* Close the file */ 
+4

複製的[讀取文本文件到C中的陣列(http://stackoverflow.com/questions/410943 /讀一個文本文件到一個數組在c) – 2010-06-04 16:20:12

+0

實際上我想要的是整個文本文件內容被保存在一個字符數組中,而不是打印,,我想使用數組的字符後來 – 2010-06-04 16:21:43

+2

Nadeem,請參閱接受的答案tha他有聯繫。這是你想要的。基本上,字節char *是你正在談論的數組,你可以隨心所欲地做任何事情,直到你釋放它爲止。 – 2010-06-04 16:47:35

回答

2

另一解決方案是映射整個文件到存儲器中,然後把它作爲一個字符數組。

在windows下MapViewOfFile和UNIX mmap下。

一旦你映射文件(大量的例子),你會得到一個指向內存中的文件的開頭。將其轉換爲char[]

0

由於您不能假定文件有多大,您需要確定大小,然後動態分配一個緩衝區。

我不會發布的代碼,但這裏的總體方案。使用fseek()導航到文件的末尾,使用ftell()來獲取文件的大小,再使用fseek()來移動文件的開頭。使用您找到的大小爲malloc()分配char緩衝區。使用fread()將文件讀入緩衝區。當你完成緩衝區時,釋放()它。

0

使用不同的開放。即

fd = open(str[1], O_RDONLY|O_BINARY) /* O_BINARY for MS */ 

read語句將用於字節緩衝區。

count = read(fd,buf, bytecount) 

這將做一個二進制文件打開和讀取。

3

您需要確定文件的大小。一旦你有了,你可以分配一個足夠大的數組並且一次讀取它。

有兩種方法來確定文件的大小。

使用fstat

struct stat stbuffer; 
if (fstat(fileno(filecommand), &stbuffer) != -1) 
{ 
    // file size is in stbuffer.st_size; 
} 

隨着fseekftell

if (fseek(fp, 0, SEEK_END) == 0) 
{ 
    long size = ftell(fp) 
    if (size != -1) 
    { 
     // succesfully got size 
    } 

    // Go back to start of file 
    fseek(fp, 0, SEEK_SET); 
}