Solved

cant read a number by number from a file in C

Posted on 2004-09-27
13
264 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

690 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