Solved

cant read a number by number from a file in C

Posted on 2004-09-27
13
259 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
Comment Utility
Try using fscanf(in, "%d", &number);
0
 

Author Comment

by:aja101498
Comment Utility
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
Comment Utility
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
 
LVL 3

Expert Comment

by:guynumber5764
Comment Utility
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
Comment Utility
>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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 3

Expert Comment

by:guynumber5764
Comment Utility
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
Comment Utility
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
Comment Utility
>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
Comment Utility
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
Comment Utility
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

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…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
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.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now