2010-06-04 71 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); 
}