Solved

Reading datas one by one

Posted on 2003-11-03
20
324 Views
Last Modified: 2010-04-15
hello ,

here it is :
I want to make a program so that it opens a file ( this is easy :) ) and reads the datas in it one by one.
Reading only one number or char is easy, how can I make the program so that it reads the number or chars  puts it into the function writes or prints( whatever) and goes to the second number till the EOF .
I dont want to get involved in pointers ( If this program has to be involved ) since I am new to the topic and they seem to be hard .
0
Comment
Question by:hermesc
  • 8
  • 6
  • 4
  • +2
20 Comments
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
> I am new to the topic and they seem to be hard
file handling is considered relatively advanced .... if you are a beginner, start with smaller programs... or is it your home work ?
0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
since it seems like homework, I cannot give you entire code ...
here are some hints though

1. open a file using fopen()
2. to read a single char use fgetc() ... from your problem statement it looks like you have some numbers written in the file ... something like
12 44 6666 875
if yes, then best way would be to read in a line at a time using fgets() and then use atoi() or strtol() to get the numbers
3. repeat 2 until EOF
4. close the file using fclose()

for more information on each of these functions refer to the man pages ...

if all you want is to read and print the contents of the file, then
while ( fgets(...) != NULL )
      puts( ... );
might be a better way

if you have a different scenario than what i stated above, then clarify using some sample input output
if you have any doubts, post to seek clarifications
0
 
LVL 10

Expert Comment

by:Sys_Prog
Comment Utility
As Sunnycoder said, We won't give u the code, but can help u.

Look at the help for the following functions

fopen ()
fread ()
fwrite ()
fclose ()

These would be sufficient to solve your problem

Regarding pointers, u would have to use atleast one pointer, i.e. the FILE pointer.

Otherwise, u won't require any pointer. Normal variables would suffice

Try with the above functions, post some code if u find any problem and we can help
0
 

Author Comment

by:hermesc
Comment Utility

Smaller programs? what do you mean by smaller programs :) printing the name or multiplying the number given. I have been dealing with C for only 3 months. I dont think it is early to get involved with file handling.
For homework, a think a homework is asking the whole code not looking for help . I just asked reading the file one by one and treating one by one. I have nothing said/asked  about the whole project itself.
If you know the answer or you can divert me to another address ( tutorials or etc ...) I would appreciate it.
0
 
LVL 6

Expert Comment

by:Ajar
Comment Utility
simple code to read many variables from a single line in a single go

int main()
{
      char buf[256] = "Date: 11/03/2003/02:31AM PST";
      //you can read individual characters  like
      char dd[4],mm[4],yy[6],hh[4],MM[4],u[128];//u stands for dummy useless
      sscanf(buf,"%6s%2s%1s%2s%1s%4s%1s%2s%1s%2s",u,dd,u,mm,u,yy,u,hh,u,MM);
      printf("%s %s %s %s %s %s",dd,mm,yy,hh,MM);
}
0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
>I just asked reading the file one by one and treating one by one
man fgetc

http://www.cs.cf.ac.uk/Dave/C/CE.html
0
 
LVL 10

Expert Comment

by:Sys_Prog
Comment Utility
0
 
LVL 10

Expert Comment

by:Sys_Prog
Comment Utility
0
 

Author Comment

by:hermesc
Comment Utility
yes the way I thought was using getchar but isnt there a simpler way?

0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
if you wish to read in char by char, I guess there is no simpler way that having to read individual chars!!! ;o)
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
arrrgh.... typos make it unreadable

since you wish to
"I just asked reading the file one by one and treating one by one."

There is no simpler way than having to read in char by char as has been suggested
0
 

Author Comment

by:hermesc
Comment Utility
#include <stdio.h>
int main()
{
    FILE *in;
    int a;
    if ((in = fopen("file.txt", "r")) == NULL)
    {
        puts("Unable to open the file");
        return 0;
    }
    while (!feof(in))
    {
        int num;
        a = fgetc(in);
        num=atoi(a);
     function();
       
    }
    fclose(in);
    return 0;
}

function()
{
int num;
num=num*2;
printf("%d",num);
}

what can be the reason?

in file.txt there is only 5 and the output is 408408408

sunnycoder : you said get in one line how will I seperate then? wont it be hard?



0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
>function()
{
int num;
num=num*2;
printf("%d",num);
}

num is uninitialized !!! you perhaps want to pass it an argument

>num=atoi(a);
you are passing int parameter to atoi while it expects a string

> you said get in one line how will I seperate then? wont it be hard?
not at all

fgets (...); //get it in buffer
//if you have all ints then
temp = buffer; //pointer for moving through the buffer
while(1)
{
     num = strtol ( temp, endptr, 10 );   // convert into int ... use num as you want
     if ( **endptr == '\0' )   //if EOS then break
           break;
     temp = *endptr + 1;     //else convert next num
}


thats all !!!
0
 

Author Comment

by:hermesc
Comment Utility
well sunny I am totaly confused
I have looked up to fgets where it has 3 parameters
 fgets(char *s, size_t n, FILE *stream)
can you explain fgets

can you explain this part again
{
     num = strtol ( temp, endptr, 10 );   // convert into int ... use num as you want
     if ( **endptr == '\0' )   //if EOS then break
           break;
     temp = *endptr + 1;     //else convert next num
}
0
 

Author Comment

by:hermesc
Comment Utility
hello again,

I have done this in a simplier way :=)

#include <stdio.h>
#include <stdlib.h>

int main() {
  char c[1000];    
  int num ;
  FILE *file;  

  file = fopen("numbers3.txt", "r");

  if(file==NULL) {
    printf("Error: can't open file.\n");    
    return 1;
  }
  else {
   
      while(fgets(c, 10, file)!=NULL) {
      num = atoi(c);
      printf("%d\n",num);
    }
    fclose(file);
    return 0;
  }
}



only fault is this this program reads the stuff in terms of lines how can make this sensible to ' ' \n and \t
0
 
LVL 23

Expert Comment

by:brettmjohnson
Comment Utility
> only fault is this this program reads the stuff in terms of lines how can make this sensible to ' ' \n and \t

After reading the line with fgets, loop over the contents of the line using strtok() pulling each individual
token separated by whitespace.

while (fgets(c, sizeof(c), file) != NULL) {
      char *tok;
      for (tok = strtok(c, " \t\r\n"); tok ; tok = strtok(NULL, " \t\r\n")) {
            num = atoi(tok);
            printf("%d\n",num);
      }
}

Not the changes I made:
1) fgets() supplies sizeof(c) so that is may fill the entire buffer, if necessary.
2) loop over the using strtok to pull individual tokens separated by whitespace.
3) interperet each of those tokens as a number.

BTW, atoi() is deprecated, using strtol() as sunnycoder mentioned is preferred.
Using strtol, you can get an indication that the token was not numeric.  It also
parses numbers in other radixes.
Using atoi(), "0", "0.1234", "0x1F7E", and "Hello"  will all return the numeric value 0 .



0
 
LVL 10

Expert Comment

by:Sys_Prog
Comment Utility
Here's the help for strtol

Function: long int strtol (const char *restrict string, char **restrict tailptr, int base)

The strtol ("string-to-long") function converts the initial part of string to a signed integer, which is returned as a value of type long int.

This function attempts to decompose string as follows:


·      A (possibly empty) sequence of whitespace characters.  Which characters are whitespace is determined by the isspace function .  These are discarded.

      ·      An optional plus or minus sign (+ or -).

      ·      A nonempty sequence of digits in the radix specified by base.


If base is zero, decimal radix is assumed unless the series of digits begins with 0 (specifying octal radix), or 0x or 0X (specifying hexadecimal radix); in other words, the same syntax used for integer constants in C.

Otherwise base must have a value between 2 and 36.  If base is 16, the digits may optionally be preceded by 0x or 0X.  If base has no legal value the value returned is 0l and the global variable errno is set to EINVAL.


·      Any remaining characters in the string.  If tailptr is not a null pointer, strtol stores a pointer to this tail in *
tailptr.

If the string is empty, contains only whitespace, or does not contain an initial substring that has the expected syntax for an integer in the specified base, no conversion is performed.  In this case, strtol returns a value of zero and the value stored in *tailptr is the value of string.



Exaplination

Basically he is parsing the string of integers [got using fgetc()] for integers one at a time. The Long Integer is returned and the remaining string is stored in the second argument to strtol

This in your case, endptr (which is char**) will store the remaining string and num will a number

This while loop is to be run for every line


Hope this helps

0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
hermesc were you able to understand or do you need more help ?
0
 

Author Comment

by:hermesc
Comment Utility
I am totally out of the event .Anyway, thanks for your all valuable help.I have to learn this file handling deeply.Maybe ,I should start from the beginning.I should give the input line by line :=)
0
 
LVL 45

Accepted Solution

by:
sunnycoder earned 350 total points
Comment Utility
that is a wise decision....
however, if you have no more queries regarding this question, pls close it by accepting answer(s)
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
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…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

728 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

10 Experts available now in Live!

Get 1:1 Help Now