Sunday, July 12, 2009

Help with Opening file in C.?

Im having a problem here. I have a little project to do but having some problems. The question simply asks me to prompt the user for a filename. after i get that i need to open the file and read in the information line by line and add the values of some numbers.





This is what I have





#define MAX 30


FILE *ifp;





int main(){





int num;





int scores;


char filename[MAX],c;





printf("Please enter filename to open\n");


scanf("%s",%26amp;filename);





ifp = fopen("filename","r");





fscanf(ifp,"%d",%26amp;num);





while(num!=0)


{





fscanf(ifp, "%d",%26amp;scores);


scores+=scores;


}


printf("scores are: %d\n",scores);











fclose(ifp);








return 0;


}








everytime i try it it shows 0 when printed out onscreen. the file i have only have the number below in that order.





500


345


323

Help with Opening file in C.?
scanf(%s, filename); // yah, you can remove the %26amp;





ifp=fopen(filename,"r"); // remove quotes from filename





fscanf(ifp,"%d",%26amp;num); // if the first num is 500 in your file, you will spin in the loop forever, i.e.





while(num!=0) // no way to get out of this since num == 500
Reply:You should remove the %26amp; character *only* from:


scanf("%s",%26amp;filename);





The while loop will go forever, since you read into num only one time and then it never gets modified.





Replace it with this loop:


while(num!=0)


{


scores+=num;


fscanf(ifp, "%d",%26amp;num);


}


So you keep reading into num, but adding its value to scores, which you have to initialize to 0, so the nums don't get added to some random value that scores may have upon declaration.


int scores = 0;





Oh, and you should read a new num, after you have added the first num read before entering the loop, otherwise you will lose the first value.





That should work. Good luck!





LATER EDIT: check back since I did some mistakes myself!
Reply:You should use


scanf("%s",filename);





You don't need the "%26amp;" because it is already a pointer.





Any array is already a pointer and char is no exception.





I don't see any other problems in there except that you should check ifp after you do the fopen and if it is null then warn that the file was not opened.

bouquet

No comments:

Post a Comment