Solved

cant read a number by number from a file in C

Posted on 2004-09-27
13
262 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
fix34  challenge 9 148
groupSum5 challenge 5 91
Way to decrease size of apk file 9 88
Test the speeds on my PC Drives 12 63
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

821 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