I would like to write a program that can continuously 1 to ID once user registered a user. I use for loop
to design it, but I don't know how to break the loop after registered a user. Please help me.
Expected Data in idtest.txt:
SID001:USER1
SID002:USER2
SID003:USER3
.
.
and so on
Actual Data in idtest.txt:
SID001:USER1
SID002:USER1
SID003:USER1
.
until SID00999:USER1
My Code:
int main()
{
FILE* f;
char data[1024], user[50];
int num = 0, c, buf;
printf("Enter User: ");
scanf("%s", user);
f = fopen("idtest.txt", "a ");
while (fgets(data, sizeof data, f));
for (buf = 1; buf <= 999; buf )
{
c = fgetc(f);
if (c == EOF)
{
fprintf(f, "SID00%d:%s\n", num, user);
}
else if (num >= 1)
{
fprintf(f, "SID00%d:%s\n", num, user);
}
else if (num >= 9)
{
fprintf(f, "SID0%d:%s\n", num, user);
}
else if (num >= 99)
{
fprintf(f, "SID%d:%s\n", num, user);
}
break;
}
return 0;
}
CodePudding user response:
There are multiple problems in your code:
- you do not test for errors
- as coded,
num
is always0
: the program cannot produce the file contents posted. - it makes no sense to try an read the next byte with
fgetc(f)
since the previous loop reached the end of the file already. This call returnsEOF
, which explains why you always write 2 leading zeroes. - you cannot mix reading and writing operations without an intervening seek operation, it has undefined behavior. Your code manages to write to the file, but it might behave differently with a different compiler / library / operating system...
- you can simplify the output code using
d
to format numbers with leading zeroes. - naming an
int
variablebuf
is very confusing.
If you intend for the program to register one user at a time, you should read the file and count the number of lines, then write a single entry at the end.
Here is a modified version:
#include <stdio.h>
int main() {
char user[50];
char data[1024];
FILE *f;
int num;
printf("Enter User: ");
if (scanf("Is", user) != 1) {
fprintf(stderr, "invalid or missing input\n");
return 1;
}
f = fopen("idtest.txt", "a ");
if (f == NULL) {
fprintf(stderr, "cannot open file idtest.txt\n");
return 1;
}
/* count the number of users */
num = 1;
rewind(f);
while (fgets(data, sizeof data, f)) {
num ;
}
/* switch to writing mode */
// No need to seek because the above loop hit the end of file.
// which is a special case where the nextcall can be a write operation
//fseek(f, 0L, SEEK_CUR);
fprintf(f, "SIDd:%s\n", num, user);
fclose(f);
return 0;
}