-3

I’m trying to write a function which reads a file name (par.dat) and prints to screen a value written into the file. This value can be an integer such as 12. However, my code is prints to screen only “0” value. Can someone show me how to fix this?

#include<stdio.h>
#include<stdlib.h>

int foo( const char *argv){
   FILE *fp;
   char c[25];
   FILE *fptr;
   fptr = fopen(argv, "r");
   fscanf(fptr,"%[^\n]", c);
   fp = fopen(c, "r");
   fscanf(fp, "%d", &num);
   printf("%d\n", num);
   fclose(fptr);
   }

int main(){
int num;

foo("par1.dat");

    return 0;
}
kemal
  • 3
  • 1
  • Why do you have two calls of `fopen`? (and only one `fclose`) – Support Ukraine Nov 30 '18 at 16:55
  • How did you compile this code ? The function `foo` has no variable `num` – Support Ukraine Nov 30 '18 at 16:56
  • Possible duplicate of [Failed to read integer using fscanf in c](https://stackoverflow.com/questions/13100014/failed-to-read-integer-using-fscanf-in-c) – fdk1342 Nov 30 '18 at 16:59
  • Right now you're trying to read file that is inside par1.dat file so if you have 12 in par1.dat you will read file "12". Also `num` is inside `main` it should be in `foo`. – jcubic Nov 30 '18 at 16:59
  • 1
    Show the actual source code that is exhibiting the problem. (The source code in the question cannot be it because it does not compile because `num` is not declared before it is used.) Show the exact contents of ”par1.dat”. If the intent is to open another file using a name from “par1.dat”, show the exact contents of that file. – Eric Postpischil Nov 30 '18 at 17:02

1 Answers1

0

You could do something like this!

      #include <stdio.h>

void foo(const char *filename)
{
   FILE *par = fopen(filename, "r");
   int num;
   if(par != NULL)
   {
        fscanf(par, "%d", &num);

        fclose(par);
        printf("%d\n",num);
   }
   else
   {
      perror(filename);
   }
}
int main(void)
{
   const char filename[] = "par.dat";
   foo(filename);
   return 0;
}
CMan
  • 16
  • 1