fgets 清除我的 C 文件的内容并且不允许我打印到文件
fgets clears the contents of my C file and doesn't allow me to print to a file
我正在编写一个简单的 c 程序来为学生添加、显示和修改记录。它生成一个 .txt 文件,该文件接受记录。
长话短说,我已经设法找出哪个函数正在清除我的文件,它是 fgets。出于某种奇怪的原因,fprintf 正常工作,直到我到达 fgets,然后每次使用它时都会继续清除我的文件。为此绞尽脑汁4天
int main(int argc, char *argv[])
{
int changes = 1; /* numbers of changes made to text file */
FILE *f;
f = fopen(argv[1], "wb+");
fprintf(f, "this is a success");
if (argc < 2) {
printf("You dun goof'd.");
exit(1);
}
if (f == NULL)
exit(1);
input_again(f, changes);
error(f, changes);
fclose(f);
return 0;
}
void input_again(FILE *f, int quantity)
{
char command[MAX];
/*char cmd[25];
char arg1[30];
char arg2[30];
char arg3[30];*/
int changes = quantity;
fprintf(f, "input again%d", changes);
while ((fgets(command, MAX, stdin)) != NULL) { /* file gets cleared after input */
printf("%s", command);
sscanf(command, "%s %s %s %s", cmd, arg1, arg2, arg3);
if (strlen(arg1) > 21 || strlen(arg2) > 21 || strlen(arg3) > 21)
error(f, changes);
if (strcmp(cmd, "add") == 0) {
fprintf(f, "add");
add(f, arg1, arg2, arg3, changes);
printf("%d", changes);
} else if (strcmp(cmd, "display") == 0) {
display(f, arg1, changes);
} else if (strcmp(command, "modify")== 0) {
modify(f, arg1, changes);
} else {
error(f, changes);
}*/
}
}
我正在使用 cygwin 来编译我的程序。如果我调用代码的方式存在简单问题,请告诉我。
您正在写入在命令行 argv[1]
上命名的文件,但是
你是说要读stdin吗?那不会读取您刚刚写的内容。
我正在编写一个简单的 c 程序来为学生添加、显示和修改记录。它生成一个 .txt 文件,该文件接受记录。
长话短说,我已经设法找出哪个函数正在清除我的文件,它是 fgets。出于某种奇怪的原因,fprintf 正常工作,直到我到达 fgets,然后每次使用它时都会继续清除我的文件。为此绞尽脑汁4天
int main(int argc, char *argv[])
{
int changes = 1; /* numbers of changes made to text file */
FILE *f;
f = fopen(argv[1], "wb+");
fprintf(f, "this is a success");
if (argc < 2) {
printf("You dun goof'd.");
exit(1);
}
if (f == NULL)
exit(1);
input_again(f, changes);
error(f, changes);
fclose(f);
return 0;
}
void input_again(FILE *f, int quantity)
{
char command[MAX];
/*char cmd[25];
char arg1[30];
char arg2[30];
char arg3[30];*/
int changes = quantity;
fprintf(f, "input again%d", changes);
while ((fgets(command, MAX, stdin)) != NULL) { /* file gets cleared after input */
printf("%s", command);
sscanf(command, "%s %s %s %s", cmd, arg1, arg2, arg3);
if (strlen(arg1) > 21 || strlen(arg2) > 21 || strlen(arg3) > 21)
error(f, changes);
if (strcmp(cmd, "add") == 0) {
fprintf(f, "add");
add(f, arg1, arg2, arg3, changes);
printf("%d", changes);
} else if (strcmp(cmd, "display") == 0) {
display(f, arg1, changes);
} else if (strcmp(command, "modify")== 0) {
modify(f, arg1, changes);
} else {
error(f, changes);
}*/
}
}
我正在使用 cygwin 来编译我的程序。如果我调用代码的方式存在简单问题,请告诉我。
您正在写入在命令行 argv[1]
上命名的文件,但是
你是说要读stdin吗?那不会读取您刚刚写的内容。