Solved

cant read a number by number from a file in C

Posted on 2004-09-27
13
261 Views
Last Modified: 2013-11-08
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
Comment
Question by:aja101498
  • 4
  • 2
  • 2
  • +1
13 Comments
 
LVL 3

Expert Comment

by:guynumber5764
ID: 12164059
Try using fscanf(in, "%d", &number);
0
 

Author Comment

by:aja101498
ID: 12164245
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
 
LVL 55

Accepted Solution

by:
Jaime Olivares earned 43 total points
ID: 12164937
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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 3

Expert Comment

by:guynumber5764
ID: 12165307
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
 
LVL 8

Assisted Solution

by:ssnkumar
ssnkumar earned 41 total points
ID: 12166821
>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
 
LVL 3

Expert Comment

by:guynumber5764
ID: 12173065
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
 

Author Comment

by:aja101498
ID: 12174507
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
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 12174548
>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
 
LVL 3

Assisted Solution

by:guynumber5764
guynumber5764 earned 41 total points
ID: 12174774
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
 
LVL 8

Expert Comment

by:ssnkumar
ID: 12176634
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
countClumps  challenge 10 147
Specific format 21 198
wordappend challenge 8 179
Work with App store 7 52
Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
There is an easy way, in .NET, to centralize the treatment of all unexpected errors. First of all, instead of launching the application directly in a Form, you need first to write a Sub called Main, in a module. Then, set the Startup Object to th…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question