devxlogo

Record Retrieveal Using fscanf

Record Retrieveal Using fscanf

Question:
If three records have been written to a text file(each record having 3 int fields) and each integer field is seperated by a comma, how do you retrieve only the int values from each record (i.e no character retrieval)and print to screen using fscanf and printf?

For example, the file contains:
1,2,3,
4,5,6,
7,8,9,

The screen output should be:
1 2 3
4 5 6
7 8 9

Answer:
Although it isn’t used much by C++ developers these days, scanf and fscanf provide a lot of functionality.

My preference would be to read each line into a buffer and then call sscanf. This gives you a little more control. But, given the file format you specified, you could easily read in the contents with the following code:

#include main(){   FILE* f;   int a, b, c;   f = fopen("c:\test.dat", "r");   if (f != NULL) {      while(!feof(f)) {         if (fscanf(f, "%d,%d,%d,
", &a, &b, &c) != 3) {            printf("Syntax error found in file.
");            break;         }         printf("%d %d %d
", a, b, c);      }      fclose(f);   }   return 0;}

See also  Redefining Energy Management: Advanced Solutions for Modern Buildings
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist