U-571
U-571

Reputation: 517

read a file for a particular input format

How to read a file in c when the given input format is

4
5
3
a,b
b,c
c,a

Please help...this my file scanning function. here m should store 4 ,n should store 5 and l should store 3. then col1 will store{abc} and col2will store{bca} m n , l are int. col1 and col2 are char arrays The third line of the file indicates a value 3 , which refers that there are three line below it and it contain 3 pairs of characters.

i = 0, j = 0;
while (!feof(file))
{
  if(j==0)
  {
    fscanf(file,"%s\t",&m);
    j++;
  }
  else if(j==1)
  {
    fscanf(file,"%s\t",&n);
    j++;
  }
  else if(j==2)
  {
    fscanf(file,"%s\t",&l);
    j++;
  }
  else
  {
    /* loop through and store the numbers into the array */
    fscanf(file, "%s%s", &col1[i],&col2[i]);
    i++;
  }
}

but my result is not coming please tell how to proceed ....

Upvotes: 0

Views: 122

Answers (2)

unwind
unwind

Reputation: 399823

A few pointers:

  1. Don't use feof(), it's never needed for code like this.
  2. Read a full line at once, with fgets().
  3. Then parse the line, using e.g. sscanf().
  4. Check the return values from I/O functions, they can fail (for instance at end of file).

Upvotes: 2

Floris
Floris

Reputation: 46375

UPDATED to allow reading of variable number of lines

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int value1, value2, value3, i;
  char *col1, *col2;
  char lineBuf[100];
  FILE* file;

  file = fopen("scanme.txt","r");

  fgets(lineBuf, 100, file);
  sscanf(lineBuf, "%d", &value1);
  fgets(lineBuf, 100, file);
  sscanf(lineBuf, "%d", &value2);
  fgets(lineBuf, 100, file);
  sscanf(lineBuf, "%d", &value3);

  // create space for the character columns - add one for terminating '\0'
  col1 = calloc(value3 + 1, 1);
  col2 = calloc(value3 + 1, 1);

  for(i = 0; i < value3; i++) {
    fgets(lineBuf, 100, file);
    sscanf(lineBuf, "%c,%c", &col1[i], &col2[i]);
  }
  fclose(file);

  printf("first three values: %d, %d, %d\n", value1, value2, value3);
  printf("columns:\n");
  for (i = 0; i < value3; i++) {
    printf("%c  %c\n", col1[i], col2[i]);
  }

  // another way of printing the columns:
    printf("col1: %s\ncol2: %s\n", col1, col2);
}

I performed none of the usual error checking etc - this is just to demonstrate how to read things in. This produced the expected output with the test file you had. I hope you can take it from here.

Upvotes: 2

Related Questions