For Programmers: Free Programming Magazines  


Home > Archive > Unix Programming > September 2005 > probelm while reading from file









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author probelm while reading from file
hirenshah.05@gmail.com

2005-09-25, 6:59 pm

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);


}}

#2pencil

2005-09-26, 7:00 pm

fp=fopen("data","r+");
if(!fp)exit(1);
else {
while(ch!=EOF) {
ch=fgetc(fp);
printf("%c",ch);
}
}
fclose(fp);

Barry Margolin

2005-09-27, 3:57 am

In article <1127679574.992429.69170@g44g2000cwa.googlegroups.com>,
hirenshah.05@gmail.com wrote:

> struct st{char ch[50];
> int n;
>
>
>
> }


Aren't you missing a ';' there?

>
>
> int main()
> {
> st *x,*y;
> int fd;
> scanf("%s\n%d",x.ch,x.n);


You've never initialized x, so you're writing into some random part of
memory. You're also using x as if it were a structure variable, not a
pointer. I think you meant your declaration to be:

st x, y;

>
> 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)))


If y is a pointer, then that should be:

while(read(fd, y, sizeof(st)))

> {
> printf("%s%d",y->ch,y->n);
>
>
> }}


--
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
Vi Si

2005-09-27, 3:57 am

Barry Very very brilliant observations I am impressed

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com