使用fscanf从文件中读取

时间:2014-03-02 08:07:20

标签: c arrays scanf

我正在尝试从输入文件中读取一系列字母,直到行尾,将字母存储在数组中,并返回每行中读取的字母数。

注意:我需要使用fscanfMAX_IN_LENGTH已经使用#define定义,输入文件已经打开以供阅读。

这就是我所拥有的:

for(i=0; i<MAX_IN_LENGTH; i++) {
 if (fscanf (input, "%c", &sequence[i]) != '\n')
 count++;
 }
return count;

3 个答案:

答案 0 :(得分:2)

fscanf()不会像您假设的那样返回它扫描的字符。它返回分配的输入项数,如果失败则返回EOF

if (fscanf(input, "%c", &sequence[i]) != EOF) {
    if (sequence[i] == '\n') { break; }
    count++;
}

答案 1 :(得分:0)

您是否阅读了fscanf的手册页?它在线 - 请参阅http://linux.die.net/man/3/scanf

您将注意到它会记录返回您正在进行的比较的值

答案 2 :(得分:0)

这是一个可能的解决方案:

#include <stdio.h>      /* fscanf, printf */
#include <stdlib.h>     /* realloc, free, exit, NULL */

#define MAX_IN_LENGTH 100

int read_line(FILE* strm, char buffer[]) {
   char ch;
   int items;
   int idx = 0;
   if(strm) {
      while((items = (fscanf(strm, "%c", &ch))) == 1 && idx < MAX_IN_LENGTH) {
         buffer[idx++] = ch;
      }
   }
   return idx;
}

int copy_data(char buffer[], int length, char** s) {
   static int current_size = 0;
   *s = (char*)realloc(*s, current_size + length+1); /* +1 for null terminator */
    memcpy(*s+current_size, buffer, length);
    current_size += length;
    return s ? current_size : 0;
}

int main(int argc, char* argv[]) {
   int line = 0;
   char buf[MAX_IN_LENGTH] = {0};
   char* array = 0;
   int idx = 0;
   int bytes_read = 0;
   if(argc == 2) {
       FILE* in=fopen(argv[1],"r");  
       while((bytes_read = read_line(in, buf)) > 0) {
           printf("%d characters read from line %d\n", bytes_read, ++line);
           idx = copy_data(buf, bytes_read, &array);
       }
       if(array) {
           array[idx] = '\0';
           printf("Complete string: %s\n", array);
           free(array);
       }
       fclose(in);
   }

   return 0;
}
相关问题