Hi everyone, Im trying to find some help with some C file i/o stuff that I cant really figure out. I'm not trying to mooch off work from people as most boards dont like, but on my other forum no one can really help me it seems. Anyways, if anyone wants to help I have a file called "cars.dat" and im trying to take the data from there and assign it to variables, thats my only problem, because it doesnt seem to be working. Heres the .dat code... PHP: John Jones 55 250 20 Mary James 67 350 10 Amy Smith 99 100 8 Joe Johns 88 123 86 Trudy Mains 56 1000 80 Mary Ames 97 238 15 And here is how I am assigning it to variables, where Im guessing where my problem is... Code: for (i=0; i<MAXNUM; i++) { fscanf(fp, "%s", &fName[i]); fscanf(fp, "%s", &lName[i]); fscanf(fp, "%d", &carNum[i]); fscanf(fp, "%d", &milesDriven[i]); fscanf(fp, "%d", &usedGallons[i]); } If anyone could help me out it would be greatly appreciated.
Too little information, but I will presume that the names are arrays of C strings and the others are arrays of int. Since a C string is an array of char, then an array of C strings is a 2D array of char. Since fscanf wants a pointer to the variables, the & (address-of) is fine for the last three. For the first two, fName and lName ARE pointers, so drop the &. As I say, though, that's based on a guess. Any time you use an input function, and particularly one that may be required to convert input to a number, check the function for success. fscanf doesn't promise to work. What if you asked it to convert zx5 to an integer? It does promise to tell you if it failed, if you but ask it. Check your documentation for how it does that. Once you break it, it stays broken until you repair it.
i wonder,why there 's no additional explanations/comments like 1)what ' s an error? 2) is MAXNUM lenght of file? if yes, then how you count it?? probrbley , mistake is not there, where you are looking it try to work with "cars.txt" instead of "cars.dat" , i dont know , if fscanf works with .dat files
fscanf works with a file pointer. It doesn't know or care what the extension was in the name used in the fopen statement. It doesn't even care if the data can be parsed according to the user's wishes. If it can, it returns the values. If it can't it fails and returns an appropriate indication. There is an implication that MAXNUM is the number of records (lines) to read. It could be arbitrarily determined or it could be determined by counting the number of lines in the file. Presumably (to avoid boundary overflows and crashes), it relates to the lengths of the arrays set aside for the data. Please do not make suggestions based on unfounded impressions you might hold, or admittedly don't know (.txt vs. .dat). That is no help to the OP and might introduce unnecessary complications.