Question:
C programming reading/writing data from/to file?
bill k
2010-09-03 17:19:27 UTC
Hello. I would like to search a text file for a person's name.If the person name I would like to add it to the end. Do I have open the file for reading and then close it and then open for appending and append if the name isn't there? The searching part is unclear to me is it just a scanf() to get name and then read the file and have what is being read put through a string compare? Some code would be very helpful.Thank you in advance.
Three answers:
2010-09-03 17:58:28 UTC
name.c:



#include

#include



const char *name = "Grandma";



int

main()

{

FILE *fp;

char temp[256];



if((fp = fopen("file.txt", "r")) == NULL) {

puts("Error reading.");

return;

}

while(fp != NULL && fgets(temp, sizeof temp, fp) != NULL)

{

if(strstr(temp, name))

puts("Found!");

}

fclose(fp);

return 0;

}



file.txt:



Grandpa

Grandma

Papa

Nanna

Santa
Unca Alby
2010-09-03 17:46:16 UTC
I would open the file for read, read the data, then close it.



If you decide you need to add something, then open the file for append, write out the data, then close it.



The only reason to keep a file open is because you have more of the same. Read, read, read, read, read, and when you're done, close. Write, write, write, write, write, and when you're done, close.



You can open the file for both reading and writing at the same time, but that can get complicated, as now you have to concern yourself with the byte position in the file of your most recent operation.



Searching can be as easy or complicated as you want to make it. If you want to keep it simple, each line of the file consists ONLY of a matchable name. E.g., you enter a name, "John Smith", and you search for "John Smith". You find "John Smith", great. But if you enter a name, "Smith", then you don't find that.



So, you open the file, you read a line, you use "strcmp" to compare the line to the name, and if they're not equal, you continue looping. Loop thru the file until you either hit EOF (End Of File) or find a matching name.



If you hit EOF before you find a match, the name wasn't there. Simple.
clora
2016-10-20 06:36:02 UTC
use a counter int i=0; and alter the at an identical time as situation at an identical time as(pointer != NULL && fgets(readin, sizeof readin, pointer) != NULL && i<3) which could get in uncomplicated terms the 1st 3 strains or if the internet site is below 3 strains, it somewhat is going to offer up in the previous that.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...