0

How would I use input from a text file so that I could use it in a function, without saving the characters into an array? As I read from the text file a 1 will come up and I will go to "setParameters", where I would enter the rest of the parameters. Also in that function, I will use malloc.(if it does not make sense let me know so that I can clarify it, also I am new to C)

int val;
int choice;
 FILE *fpointer;
fpointer = fopen("afile.txt","r");
printf("\nError Detection/Correction");
printf("------------------------------\n");

choice = fscanf(fpointer,"%d",&val);
while(choice != 3)
{
    printf("1. Enter Parameters\n2. Enter Hamming Code\n3. Quit\n");
    switch(choice)
    {
        case 1: setParameters();
            break;

        case 2: checkError();
            break;

        case 3: printf("*** Program Terminated Normally");
            break;

        default: 
            printf("Not a valid entry");
        break;

    }//end of switch statment 
Blitzman
  • 11
  • 4

1 Answers1

0

To take input from file in C (using fscanf):

You need to initialize FILE pointer using fopen and then scan each input using fopen.

FILE *fpointer;
fpointer = fopen("afile.txt","r");
int ret;
while(ret = fscanf(fpointer," %d ",&val))
{
     if(ret == EOF)
     {
          break;
     }
     else
     {
         // use val variable here in code which is taken as input from file
     }
}

here, it is important to understand what ret variable is:

  • EOF, if the pointer is reached end of file.
  • 0, if no input matched with the variable
  • >0, number of matched variables with the file input

To take input from file in C++ (using fstrean):

it is very easy to get input from a file. we just need to change cin to get input from file stream instead of standard input.

#include <fstream.h>

void main() {
    ifstream cin("afile.txt");
    int val;
    cin  >> val;

    // use val as variable in code.
}

this approach is very easy but only works in C++. it requires no file operations like fscanf . just changing cin will do the work :)

Jay Joshi
  • 868
  • 8
  • 24
  • Observations: `while(ret = fscanf(fpointer," %d ",&val) { if(ret == EOF || ret == 0)` won't compile; there's a `)` missing at minimum; and the `ret == 0` condition would never be true because the (fixed) while loop would prevent it being reached. I'd use `while ((ret = fscanf(fpointer, "%d", &val)) == 1)` which only enters the loop if the input is successful. Note that [trailing blanks in `scanf()` format strings are a UI disaster](https://stackoverflow.com/questions/19499060/) too, and the leading blank is superfluous (but otherwise harmless). – Jonathan Leffler Nov 16 '17 at 23:49