0

My program is reading a txt file that contains some information (name, product, rate, time). I need to copy the last two and write them somewhere else. The code must be in C.

This is what I wrote so far but because of the random length of the first two fields (name, product) it is not working properly.

int a=25;
while (!feof(fp)){
    fseek(fp,a,SEEK_SET);
    fgets(ratetime,100,fp);
    fputs(ratetime,fp2);
    a=a+40;     
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
F_Stain
  • 33
  • 4

2 Answers2

0

First, read why (!feof(fp)) is always wrong.

This can be replaced by using fgets() in conjunction with a while() loop:

fp = fopen(".\\somefilename.txt", "r");
if(fp)
{
    while(fgets(line, sizeof(line, fp))
    {
        // parse line to ignore first two words using strtok() or strchr()
    }
    fclose(fp);
}fclose(fp)
ryyker
  • 22,849
  • 3
  • 43
  • 87
  • That's not an answer to the question. – machine_1 Mar 16 '19 at 14:20
  • @machine_1 - it is an answer. It suggests two very viable ways to parse a line from a file to eliminate the first two words, as well as warns against a known bad construct. It is not necessary to implement the solution for an answer, just provide direction on how to address the issue. – ryyker Mar 16 '19 at 14:21
0

If you already know the format of the file you can just use fscanf, like so:

FILE* fp = fopen("input_file.txt", "r");
char name[BUFFSIZE];
char product[BUFFSIZE];
int rate;
char time[BUFFSIZE];

while(fscanf(fp, "%s %s %d %s", name, product, rate, time) != EOF)
{
    //copy them in a proper data stucture
}

fclose(fp);

EDIT: BUFFSIZE is an upper bound for the string size, if you know it. If not, you have read char by char and parse them

sebastian
  • 412
  • 1
  • 4
  • 14