0

So I want to read a file containing integers. I can read the first number but how can I read all of them? String is easy but this is different. I also want to read them in a way I can then later add them together. I edited my code and I was able to output them all but my other question is how can I select each number alone so I can add whatever I want. For example, if I want to select the first column only and add it together.

Data:

54 250 19  
62 525 38  
71 123 6 
85 1322 86  
97 235 14

Code:

#include <stdio.h>
#include <conio.h>

int main()
{
    // pointer file
    FILE *pFile;
    char line[128];

    // opening name of file with mode
    pFile = fopen("Carpgm.txt","r");

    //checking if file is real and got right path
    if (pFile != NULL)
    {

        while (fgets(line, sizeof(line), pFile) != NULL)
        {
            int a, b, c;

            if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
            {
                /* Values read, do something with them */
                printf("%d %d %d\n",a, b, c);
            }
        }

        //using fgets to read with spaces 
        //fgets(line,81, pFile);

        //printing the array that got the pfile info

        //closing file
        fclose(pFile);        
    }
    else 
    {
        printf("Could not open file\n");     
    }

    getch();
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user3483718
  • 15
  • 1
  • 1
  • 7

4 Answers4

2

Read a complete line using fgets then "parse" the line using sscanf.

Something like

char line[128];
while (fgets(line, sizeof(line), pFile) != NULL)
{
    int a, b, c;

    if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
    {
        /* Values read, do something with them */
    }
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • so how can i print all of them out just to make sure they are read – user3483718 May 02 '14 at 06:03
  • @user3483718 If `sscanf` returns `3` then you are guaranteed that you have three values. But if you desperately want to print them, just do it? One by one in three `printf` calls, or as a single `printf` call printing all three. – Some programmer dude May 02 '14 at 06:14
1

The best way is probably to either read a single number at a time with fscanf(), and let it skip the whitespace (and newlines) as needed.

Or, you could read a whole line with fgets() and then parse/tokenize that line, I would use strtol() for that in this case since it makes it trivial to continue to the next nmumber. This approach will limit you to a maximum line length though, which the fscanf() approach will not.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Read whole line using fscanf and then add all of them.

You can do it as below:

//using fscanf to read 
while(EOF != fscanf(pFile,"%d %d %d", &a, &b, &c))
{
   //Add all of them
   line = a+b+c;

   //printing the array that got the file info
   printf("%d",line);

   //So it will help to remove trailing "\n" and at the end it will help to come out of loop.
   if (EOF == fgetc(fp))
   {
      break;
   }
}
ravibhuva9955
  • 199
  • 1
  • 11
  • 1
    No; [`while (!feof(file))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). The rest was good...or would be if you tested the continuation correctly with `while (fscanf(pFile, "%d%d%d", &a, &b, &c) == 3) { … }`. Note that the trailing `\n` is a very bad idea if the input will be interactive (user typing). It is OK (but unnecessary) here as the input is explicitly from a file. – Jonathan Leffler May 02 '14 at 06:18
  • @Jonathan Leffler: Thanks for your comments. – ravibhuva9955 May 02 '14 at 06:27
  • Note the difference between your loop condition (comparing with EOF) and the one I postulated (comparing with 3). Yours will lead to an infinite loop if there's a letter in the data, because the file is not at EOF, so `fscanf()` will report 0 items converted. My condition, comparing for the expected number of items to be converted, will break when `fscanf()` can't read 3 items (because of the letter in the data). – Jonathan Leffler May 02 '14 at 13:59
0
#include <stdio.h>
#include <conio.h>

int main()
   {
   FILE *pFile;

Instead of reading only one integer on the line, read all three at once.

// int line;
   int v1, v2, v3;

   // opening name of file with mode
   pFile = fopen("Carpgm.txt","r");
   if(NULL == pFile)
      {
      fprintf(stderr, "Could not open file\n");
      goto CLEANUP;
      }

Added a loop to read all lines.

   for(;;)
      {

Use 'elementsRead' to know when the 'End-Of-File' or 'EOF' has been reached.

      int elementsRead;
      //using fscanf to read

Now reading all three numbers (at the same time).

      elementsRead=fscanf(pFile,"%d %d %d", &v1, &v2, &v3);
      if(EOF == elementsRead)
         break;

      //printing the array that got the pfile info

Now printing all three numbers (at the same time).

      printf("%d %d %d\n", v1, v2, v3);
      }

CLEANUP:

   if(pFile)
      fclose(pFile);

   getch();

   return 0;
   }
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
  • Note that if there's a letter in the input file, `fscanf()` will not return EOF but will return 0 (no items converted to a number successfully). Your condition should, therefore, be `if (elementsRead != 3)`; that covers the malformatted file as well as EOF. – Jonathan Leffler May 02 '14 at 14:03
  • I'm also not a fan of labels in general, and this CLEANUP label in particular. In this context, you can either `return EXIT_FAILURE;` or `exit(EXIT_FAILURE);` in lieu of the `goto`; both terminate the program. In general, you can return from a function with an error indication. You then don't need the condition on `fclose()`; you won't execute it except when it was not null. Indeed, the label could be before `getch()`. – Jonathan Leffler May 02 '14 at 14:06