Re: problem in reading from file

From: Ed Morton (morton_at_lsupcaemnt.com)
Date: 09/26/05


Date: Sun, 25 Sep 2005 17:35:42 -0500

hirenshah.05@gmail.com wrote:
> struct st{char ch[50];
> int n;
> }
>
> int main()
> {
> st *x,*y;
> int fd;
> scanf("%s\n%d",x.ch,x.n);
>
> fd=open("data",........)
> close(fd);
> fd=open("data",O_APPEND...)
> write(fd,&x,sizeof(st));
> close(fd);
> fd=open("data",...)
>
> // here i am facing problem. every time i run the program i am writing
> some data in file. but i want read data of whole file from start till
> end and display is on screen. but it is printing only entry added
> during program(i.e. last enrty).
> //
>
> while(read(fd,&y,sizeof(st)))
> {
> printf("%s%d",y->ch,y->n);
> }}
>

When you declare x and y like this:

        st *x,*y;

you're declaring POINTERS, not structures, so you don't have any memory
allocated to hold structures, so when you invoke scanf() and try to
populate the structures that you don't have, you're just writing to
random memory locations with unpredictable results. You're compiler is
almost certainly warning you about this. Fix this first, then see if
you're still having problems.

        Ed.



Relevant Pages

  • Re: Rookie Student C++ Array question (reading from a file)
    ... >Start by writing down in plain english words what needs to be done. ... >int main ... >That's your overall plan. ... at the previous suggestion of mapping, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Rookie Student C++ Array question (reading from a file)
    ... >Start by writing down in plain english words what needs to be done. ... >int main ... >That's your overall plan. ... >do the additions inline in your real source code) ...
    (alt.comp.lang.learn.c-cpp)
  • Re: read and write columns
    ... You attempt to open the same file, "data", for writing and reading, ... Read the documentation for fscanf. ... int main ...
    (comp.lang.c)
  • Re: memory and subroutines
    ... might call a "constructor," consider writing a companion ... "destructor" function at the same time. ... to do one easily-described job and do it well; avoid writing ... int rand_in_range; ...
    (comp.lang.c)
  • Re: Inheritable Static methods
    ... the former encapsulates the conversion into the int type. ... writing "typeof.FullName" might not look quite as nice as "someClass.FullName". ... you've got a perfectly good alternative syntax that does _exactly_ the same thing. ...
    (microsoft.public.dotnet.languages.csharp)