Sunday, August 2, 2009

C - How do I save data in a text file?

I have made a maze game in C and am stuck on how to get a user name and save the username and score on a text file. I don't know much about string in C except that "it is an array of characters". I know a user name will need to be string so I am using this:





char username[3];


scanf("%s", username);





I am assuming the variable 'username' will be saved to a file but I do not know how to do this. Any ideas?

C - How do I save data in a text file?
You need the following basic steps:





FILE *fp; //create a file pointer


fp = fopen("file","w"); //open "file" for writing "w"





//check if the file was opened without errors


if(fp==NULL) {


printf("\nCould not open file.. aborting!!");


exit(1);


}





//write to file - you have a number of options here - read more about the functions to suit the formatting and data you need to write to file - one example below:





fprintf(fp, "%s %d", username, score)





fclose(fp); //close the file pointer once you are done writing to the file.
Reply:Use fprintf() function or fwrite() function. Refer the page given below...


No comments:

Post a Comment