Originally Posted by
voidpain()
Is there any way I could replace the sscanf with an fgets, or will fgets not be able to store the number into an integer variable? Is there any way I could bump the file pointer forward otherwise?
I am not sure of your file layout, however normally you would just read the file in line by line using fgets into some buffer and then break that up with sscanf() to effectively parse the line. So something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
struct myNode{
char name[30]; //note this isn't a pointer
int number;
};
//just used to make our file
void createFile(void);
int main(void){
//used for file line input
char inputBuffer[100]={0};
FILE* myFile;
int current=0;
//I am using an array but this would be your linked list
struct myNode myNodeArray[5];
//---------------------
//just makes our file to read in
createFile();
//open our file
myFile = fopen("example.txt", "r");
if(myFile){
//read our file in line by line
while(fgets(inputBuffer, sizeof(inputBuffer), myFile) && current < 5){
//break up our line into our structure
sscanf(inputBuffer,"%s %d", myNodeArray[current].name, &myNodeArray[current].number);
current++;
}
fclose(myFile);
}
//printf our results
for(int i = 0; i < current; i++){
printf("%s %d\n", myNodeArray[i].name , myNodeArray[i].number);
}
getchar();
return (0);
}
void createFile(){
FILE* myfile = fopen("example.txt", "w");
if(myfile){
fprintf(myfile, "John 30\n");
fprintf(myfile, "Joe 20\n");
fprintf(myfile, "Bob 15\n");
fclose(myfile);
}
}