简体   繁体   中英

Reading from file using fscanf

I am trying to read a sequence of letters from an input file until the end of a line, store the letters in an array, and return the number of letters that were read in each line.

Note: I am required to use fscanf , MAX_IN_LENGTH has already been defined using #define , and the input file has already been opened to read.

Here is what I have:

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

fscanf() doesn't return the character it scans like you assumed. It returns the number of input items assigned, or EOF if it fails.

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

Have you read the manual page for fscanf ? It is online - see http://linux.die.net/man/3/scanf

You will note that it will note return the value of the comparison that you are doing

Here is a possible solution:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM