0

How to avoid reading semicolon ; in FILE and save them in variable?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char gstitem[6], gstname[30],;
int gstquant, itemquant;
float gstprice;

char string[10];
printf("Purchase items fuction\n\n");
FILE *gstPtr;   //pointer to the gst.txt
gstPtr = fopen ( "gst.txt", "r+" );
printf("Enter an item code: ");
fgets(string,10,stdin);
(!feof(gstPtr));
{   

    fscanf(gstPtr,"%[^;]s %[^;]s %[^;]f %[^;]d\n",gstitem,gstname,&gstprice,&gstquant);
    printf("%s  %s  %f  %s\n",gstitem,gstname,gstprice,gstquant);
    }
fclose(gstPtr);
}

This is the file that i want to fscanf vv

gst.txt

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Your image is a small amount of text: please post it as text as part of the question. The idea of the [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) is so that readers can copy and try the code, and its input data. – Weather Vane May 31 '16 at 16:36
  • 1
    Not checking the result of `fscanf()` is the [_Road to Perdition_](http://www.dictionary.com/browse/perdition), – chux - Reinstate Monica May 31 '16 at 16:42
  • What is the purpose of `fgets` before the loop? And what is the loop control `(!feof(gstPtr));` [sic] supposed to be? Apart from being cautious about the [use of `feof`](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) the way to control the loop is with the return value from `fscanf`, such as `while(fscanf(...) == 4) {...}` – Weather Vane May 31 '16 at 16:43
  • 2
    ... or by reading a whole line with `while fgets(line, sizeof line, gstPtr) != NULL) { /* now process with sscanf */ }` – Weather Vane May 31 '16 at 16:54

1 Answers1

3

Problems with the format string:

  1. When you use the %[^;] format specifier, you should not add s to it. It is implied that the expected data is string.

  2. Using %[^;] without specifying a width can lead to reading more data than your variable can hold. Always specify the maximum number of characters you expect to read.

  3. Use of %[^;]d and %[^;]f does not allow you to read an int and a float.

  4. Avoid using \n in the format string. That will lead fscanf to read and discard all characters until the next non-whitespace character. It does not read just the newline character. It is better to add another line to skip everything until and including the newline.

Use:

fscanf(gstPtr,"%5[^;];%29[^;];%f;%d",gstitem, gstname, &gstprice, &gstquant);
int c;
while ( (c = fgetc(gstPtr)) != EOF && c != '\n');
R Sahu
  • 204,454
  • 14
  • 159
  • 270