0

hi i am writing a program that reads integers(signed or unsigend) from file.
my input file contains these numbers(without brackets)
[41 35 -66 -124 -31 108 -42 -82 82 -112 73 -15 -15 -69 -23]

and my code is:

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
FILE * hFile;
int c; 
long n  = 0;
hFile = fopen("input15Numbers.txt", "r");
if (hFile == NULL)
{
     printf("Failed to Open the File");
}
else
{
while (!feof(hFile)) {
      c = fgetc (hFile);
      if (c != ' ')
      {
         fscanf (hFile, "%i", &c);
         printf("%i", c);
         printf("\n");
         }


fclose(hFile);

getch();
}
}

But it produce wrong out put when i print it..
Output:
1
5
66
124
31
0
-42
82
2
112
3
15
15
69
23

printing some values correctly but not all, what i am doing wrong here????

2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by gerard4143
0

You could simplify your program like below:

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

int main(int argc, char**argv)
{
  char num[10];
  FILE *fd;
  
  if (!(fd = fopen("testdata", "r")))
  {
    fputs("could not open file!\n", stderr);
    exit(EXIT_FAILURE);
  }
  
  while (fscanf(fd, "%s", num) != EOF)
  {
    fprintf(stdout, "num->%s\n", num);
  }
  
  fclose(fd);
  exit(EXIT_SUCCESS);
}

This works for a text file not a binary file...

Edited by gerard4143: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.