• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 268
  • Last Modified:

cant read a number by number from a file in C

Hi

I am trying to write a program in C or converting from FORTRAN to C. I am happy to use fortran but I was forced to do this. I used the following to read some data but it is not reading the numbers one by one (12, 20, etc..) but its reading the whole line. Caan somebody help please. I want to read and process each value.Thanks

INPUT file
rain.txt file
=======
12 20 33 1 4
3 2 22 20 8

#include <stdio.h>
int main()
{
    FILE *in;
    int key;
    if ((in = fopen("rain.txt", "r")) == NULL)
    {
        puts("Unable to open the file");
        return 0;
    }
    while (!feof(in))
    {
        key = fgetc(in);
                              */
        if (!feof(in))
            putchar(key);
    }
    fclose(in);
    return 0;
}

 
0
aja101498
Asked:
aja101498
  • 4
  • 2
  • 2
  • +1
3 Solutions
 
guynumber5764Commented:
Try using fscanf(in, "%d", &number);
0
 
aja101498Author Commented:
Thznks guynumber5764. Do u mean like this

#include <stdio.h>
int main()
{
    FILE *in;
    int key;
int number;
    if ((in = fopen("rain.txt", "r")) == NULL)
    {
        puts("Unable to open the file");
        return 0;
    }
    while (!feof(in))
    {
      fscanf(in, "%d", &number);
                              */
        if (!feof(in))
            putchar(key);
    }
    fclose(in);
    return 0;
}

0
 
Jaime OlivaresCommented:
If your table has a fixed number of columns, then fscanf is a good alternative as stated by guynumber, but you have to read all at a time. Something like:

fscanf(in, "%d %d %d %d %d", &n1, &n2, &n3, &n4, &n5);
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
guynumber5764Commented:
Where I said "number" read "key".  Something like...

    while (!feof(in))
    {
      if (fscanf(in, " %d", &key)==1)
            printf("%d", key);
    }
    fclose(in);

Note that you may need spaces before or after the %d.  The only reason you should have to parse the whole line at once if you got it using fgets() (which is the better way to go but more complicated).  Check the printf manual page for more information on formatted input/output.  I'll actually try this when I have a chance.
0
 
ssnkumarCommented:
>Note that you may need spaces before or after the %d.
(spaces) This is not necessary.
In this case it will work with just:
fscanf(in, "%d", &key);

-ssnkumar
0
 
guynumber5764Commented:
ssnkumar...thanks.

aja...
It occurred to me last night that you might be misunderstanding how C IO works.  Your program,as written simply reads a file outputs it to the console one byte at a time.  The int return value and argument to getchar()/putchar() is a red herring: you are actually reading & writing bytes.

So, with your test data it would read the first byte (an ascii '1') and output it.  Then a '2', then a ' '(space) etc.  When it gets to the end of line it will read the '\n'(newline) and output that etc. until it passes the eof() test.  It doesn't matter whether your input file contains lists of numbers, the text of Moby Dick or even image data: the result is an exact copy of your file.

The various scanf() functions provide one way to interpret text data files.  Essentially you are saying "find a string of text with this format and interpret it as..."  Jaime's suggestion, for example would be perfect if your data represents 5-tuples.  The only problem with scanf() is that it is too rigid to handle mis-formatted data well.
0
 
aja101498Author Commented:
jaime_olivares ........Thanks

Yes my text file has a fixed number of cols and rows.so the fscanf(in, "%d", &key); should be in a for loop ?


guynumber5764 .....thanks

No I dont want to use getchar and putchar.
Also I do not want to read from the text just output it. that was just one way of trying to figure out what I am writing. Only I wanted is to read number by number and process it (e.g., square it and write it in an output file).Thanks  
0
 
Jaime OlivaresCommented:
>Yes my text file has a fixed number of cols and rows.so the fscanf(in, "%d", &key); should be in a for loop ?
No need for a loop, just do read all at a time, as I suggested:

int n1,n2,n3,n4,n5;
fscanf(in, "%d %d %d %d %d", &n1, &n2, &n3, &n4, &n5);

or if you want, store numbers in an array:

int n[5];
fscanf(in, "%d %d %d %d %d", &n[0], &n[1], &n[2], &n[3], &n[4]);

0
 
guynumber5764Commented:
Is your data just a series of numbers or are they logically grouped in records (tuples)?

In the former case, the single read is better since it doesn't care about the data format beyond it being a series of numbers.  It also reduces the amount of code and the chances of a mistake.  If the numeric positions are relevant (ie: the five values on a line taken together represent a data record) parsing the whole line at once is better for the same reasons.  In that case, you could even go one step farther and read an entire line with fgets() then parse it with sscanf() (a very common construct).

Either way you should use a loop to read your data.  In the first case you'll get a number at a time, in the second, you get a record (several numbers) at a time.
0
 
ssnkumarCommented:
You have got a table in a file, which you want to store in an array. This is your question right?
If you want to store in a single dimention array do like this:

int arr[100];
int i = 0;

fp = fopen();
while (!feof(fp))
{
    fscanf(fp, "%d", &(arr[i]));
    i++;
}

If you want to store in a double dimention array, do like this:

#define ROW 20
#define COL 5
int arr[ROW][COL];
int i = 0, j = 0;

fp = fopen();
while (feof(fp))
{
    fscanf(fp, "%d", &(arr[i][j]));
    j++;
    if (j == COL)
    {
        j = 0;
        i++;
    }
}

In both the cases, you will be using only fscanf() and a single while()  loop.

Hope this helps.

-ssnkumar
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now