Reputation: 45
I'm trying to insert separator for my input when storing if to a file but I'm getting error. When I try to insert with space, it seems ok. But with no space, still error.
Here's my code with space for storing input student.name and student.pass:
fprintf(fp, "%s %s\n", student.name, student.pass);
fclose(fp);
and when I check it:
while(fscanf(fp, "%s %s", &student.name, &student.pass) != EOF)
{
printf("Username is %s : Password is %s\n", student.name, student.pass);
if(strcmp(student.name, a)==0)
{
printf("Exists");
}
else
{
printf("Not Exists");
}
}
the output:
name: name;
pass: pass;
Username is name : Password is pass;
Working fine with space, but I need separator because when I try to input:
name: my name;
pass: pass;
Username is my : Password is pass;
Username is name : Password is pass;
How do I fix this with separator using '|' as separator, I prefer if the input will be like this:
fprintf(fp, "%s|%s\n", student.name, student.pass);
fclose(fp);
Upvotes: 1
Views: 93
Reputation: 37512
%s
reads data until white character is encountered. So your data can't use space if you are using such data format.
One way to fix it is to update data format and use advanced format string (C style code):
int StudentWrite(FILE *f, Student *student) {
return 2 == fprintf(f, "%s\n%s\n", student->name, student->pass);
}
int StudentRead(FILE *f, Student *student) {
return 2 == fscanf(f, "%[^\n]%*c%[^\n]%*c", student->name, student->pass);
}
Where this format string works like this:
%[^\n]
read all characters, until end line \n
%*c
read single character and discard it. Since previous format reads all but not end line character, end line character is read and discarded.To protect data from buffer overflow scanning format string can look like this: %80[^\n]%*c%80[^\n]%*c
where 80
indicates capacity of target like student->name
(remembered that you have to count terminating zero, so actual size of buffer must be by one greater then this value).
Upvotes: 3