DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   Reading data from a textfiletype (http://www.daniweb.com/forums/thread74510.html)

RisTar Apr 7th, 2007 6:44 am
Reading data from a textfiletype
 
Im trying to read some integers values from a text file.
The problem is that first lines of the text files contains some text and only then theres the values that i want to read into variables , and i dont know how to get down three lines and then read using fscanf .

TEXT FILE(storeinfo.txt):
Stores Information:
Store Code Store Size Store Workers Store Income
951 1200 7 67000
952 1452 12 92833
953 800 5 41000
954 1000 6 61000
955 1500 12 100321

Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
 int code;
 int size;
 int workers;
 int total;
}store;
int main()
{
 int i;
 FILE *filein;
 char source[40];
 store storearr[5]={0};
 printf ("Enter a source filename: ");
 gets(source);
 filein = fopen (source,"rt");
 if (filein == NULL)
 {
  printf ("Unable to open sourcefile...\n");
  exit(1);
 }
 for (i=0;i<5;i++)
  fscanf(filein,"%d %d %d %d\n",&storearr[i].code,&storearr[i].size,&storearr[i].workers,&storearr[i].total);
 for (i=0;i<5;i++)
  printf ("%-15d %-15d %-15d %-15d\n",storearr[i].code,storearr[i].size,storearr[i].workers,storearr[i].total);
 fclose (filein);
 return 0;
}

~s.o.s~ Apr 7th, 2007 6:52 am
Re: Reading data from a textfiletype
 
Keep a counter which will be initialized to 1, fgets the entire line of text in a character array, skip the first two lines using the counter previously mentioned and start reading from the third line.

Read this for using fgets.

RisTar Apr 7th, 2007 8:13 am
Re: Reading data from a textfiletype
 
can you please post a code example ?

iamthwee Apr 7th, 2007 8:30 am
Re: Reading data from a textfiletype
 
#include <stdio.h> 
#include <stdlib.h>

#define MYFILE "c:\\example.txt"

int main(void)
{
  FILE *fp;
  char buf[BUFSIZ] = "blah";
  int i;
 
  if ((fp = fopen(MYFILE, "r")) == NULL)
  {
    perror (MYFILE);
    return (EXIT_FAILURE);
  }
 
  i = 0;

  while (fgets(buf, sizeof(buf), fp) != NULL)
  {
    if (i==0 || i == 1)     
      printf("Skip these\n");
    else
      printf ("Line %2d: %s", i, buf);
      i++;
  }
 
  fclose(fp);
    getchar();
  return(0);
}

RisTar Apr 7th, 2007 9:25 am
Re: Reading data from a textfiletype
 
Thanks for the help guys !


All times are GMT -4. The time now is 7:58 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC