Search code examples
cfileformatscanffgets

C - Fgets &Scanf to read from a text file


#include <stdio.h>

int main() {
FILE *f;
unsigned int num[80];
int i=0;
int rv;
int num_values;

f=fopen("values.txt","r");
if (f==NULL){
    printf("file doesnt exist?!\n");
    return 1;
}

while (i < 80) {
    rv = fscanf(f, "%x", &num[i]);

    if (rv != 1)
        break;

    i++;
}
fclose(f);
num_values = i;

if (i >= 80)
{
    printf("Warning: Stopped reading input due to input too long.\n");
}
else if (rv != EOF)
{
    printf("Warning: Stopped reading input due to bad value.\n");
}
else
{
    printf("Reached end of input.\n");
}

printf("Successfully read %d values:\n", num_values);
for (i = 0; i < num_values; i++)
{
    printf("\t%x\n", num[i]);
}

return 0

}

Got the code above from another question, but having probelms editing it to suit my requirements, everytime i change it seems to error everywhere.

Its only a simple change aswell.

Example input from the file would be 12345678

87654321

1234567811

12345678

When reading in from the file using this method take tthe whole of every line when i only want it to take the first 8 hex numbers and save them.

I tryed using a fgets to get the line and than scanf to format it but the errors just get out of hand.

The idea i had in my head but just not sure how to implement is 1. Open file

  1. fgets current line

  2. scanf to format current line

    • Getting first 8 digits

    • Saving them to the array

  3. loop till end of file (rather than <80 like it is in the code above)

Im a newbee to c and to used to java.


Solution

  • Try

    char buffer[201];
    while (fgets(buffer, 200, f) != NULL)
    {
      if (strlen(buffer) > 7)
      {
         buffer[8] = 0;
         sscanf(buffer, "%x", &num[i++]);
      }
      else
      {
         /* report that the line is error ?! */
      }
    }