david
david

Reputation: 3

How to extract data from a file to be used as variables in C

In this piece of code im getting value of row and column from the user. But instead I wanted to know if i could extract these data from a file rather than manking the user input them. Is there any way to do that?

Can you please help me guys im very new to his language, and im not even sure if we could do that

file format(5 is for rows and 4 is for columns):

5,4

 printf("Please enter the number of rows that you would like to play on:");
 scanf("%d", &row);

 while (row < 3 || row >10)
 {
     fputs("Error, input a valid number: ", stderr);
     scanf("%d", &row);
 }

 printf("please enter the number of columns that you would like to play on:");
 scanf("%d", &col);

 while (col < 3 || col > 10) 
 {
     fputs("Error, input a valid number: ", stderr);
     scanf("%d", &col);
 }

Upvotes: 0

Views: 271

Answers (3)

gmatht
gmatht

Reputation: 835

Yes, the fscanf function works much like the scanf function, but allows input from a FILE. The FILE must first be opened with fopen I recommend checking that the FILE is non-null and fscanf returns non-End-Of-File so you don't have undefined behaviour if the file is missing or invalid. See for example, the following code:

#include <stdio.h>
int main(){
   FILE *fp;
   int row, col;
   fp = fopen("file.txt", "r"); /* open for "r"eading */
   if (fp) {
       if (fscanf(fp, "%d,%d", &row, &col)==2) {
           printf("%d:%d", row, col );
       }
   }
   fclose(fp);
   return 0;
}

Upvotes: 0

Fernando Surjus
Fernando Surjus

Reputation: 11

sure,the C standard library have a file system you can

Here a example on Writing and Reading to a file.

int main(void)
{
  FILE *fp;
  char buff[255];

  fp = fopen("/myfolder/myfile.txt", "w+"); /*the w+ makes the file read and write*/
  fprintf(fp, "This text is saved in the file\n");
  fputs("This is another method\n", fp);

  fscanf(fp, "%s", buff);
  printf("%s\n", buff );

  fgets(buff, 255, (FILE*)fp);
  printf("%s\n", buff );

  fclose(fp);
}

Upvotes: 0

Green-Avocado
Green-Avocado

Reputation: 891

You can access the contents of a file using a FILE pointer. The address is set using fopen() where the first argument is a char* for the file name and the second is a char* for permissions (e.g. read, write, read and write, etc.).

If you can assume that the contents of the file are valid, you can open and read two numbers from a file as follows:

FILE *fp;
fp = fopen("filename", "r");

if(fscanf(fp, "%d,%d", &row, &col) != 2)) {
    //handle error
    printf("error\n");
}

fclose(fp);

Though I would still strongly recommend validating these anyways, as well as checking that the file contains all the required data before attempting to read it.

Upvotes: 1

Related Questions