c - 虽然循环在C中被跳过
问题描述
这是我的代码,我想显示存储在文本文件中的所有行,同时通过从用户那里获取要替换的行的输入来替换该特定行。
///Get Customer ID
char c_id[100];
printf("Enter Customer ID: ");
scanf("%s", &c_id);
FILE* fPtr;
FILE* fTemp;
char temp_line[100];
char buffer[100];
char newline[100];
int i, arr_n, line, count;
/* Remove extra new line character from stdin */
fflush(stdin);
fflush(stdout);
/// Open all required files
fPtr = fopen(c_id, "r");
fTemp = fopen("replace.txt", "w");
/// Print the content
i = 1;
arr_n = 0;
printf("\nOptions:\n");
while (fgets(buffer, BUFFER_SIZE, fPtr))
{
printf("%d. %s\n", i, buffer);
i = i + 1;
}
printf("Enter your options: ");
scanf("%d", &line);
printf("Enter the updated information: ");
scanf("%s", &newline);
count = 0;
while (fgets(temp_line, BUFFER_SIZE, fPtr))
{
count++;
if (count == line)
{
switch (line)
{
case 1:
fprintf(fTemp, "Name: %s", newline);
break;
case 2:
fprintf(fTemp, "Date of birth: %s", newline);
break;
case 3:
printf("It did got here");
fprintf(fTemp, "Address: %s", newline);
break;
case 4:
fprintf(fTemp, "Contact 1: %s", newline);
break;
case 5:
fprintf(fTemp, "Contact 2: %s", newline);
break;
default:
printf("Invalid answer given");
}
}
else
{
fputs(temp_line, fTemp);
}
}
/// Close all files to release resource
fclose(fPtr);
fclose(fTemp);
/// Delete original source file
remove(c_id);
/// Rename temporary file as original file
rename("replace.txt", c_id);
printf("\nSuccessfully updated the information");
这是最后一个while
被跳过的循环。为什么它会跳过那个while循环,我似乎找不到它跳过的原因。我尝试将temp_line更改为另一个缓冲区,它仍然是一样的。
我尝试先删除一些与它无关的不必要行并尝试解决问题,但仍然找不到 while 循环被跳过的确切原因。
是因为开关盒吗?
还是缓冲区有问题?
解决方案
您的第一个循环到达文件末尾。fgets
如果到达文件末尾,函数返回指向缓冲区的指针或空指针。由于您在循环中将指针值用作布尔值,因此while
跳过第二个循环,因为您的文件已经用尽并fgets
返回 NULL。 while(NULL) { ... }
永远不会进入 while 循环代码块。
使用函数fseek
或rewind
在第二个循环之前将文件指针重置到文件顶部。
推荐阅读
- time - 检查:两个具有不同参数和时隙的 RRULE 重叠
- reactjs - 如何使用链接设置动态参数的状态
- docusignapi - 为 MDM 异常寻找 DocuSign iOS URL 协议
- javascript - RegEx 用于测试数字中的加号或减号
- vb.net - 权限问题???使用 System.IO.File.Exists
- c# - 无法将多个生成的 Html.DropDownListFor 绑定到 ViewModel
- xquery - 如何通过 xquery 在 Marklogic 中设置集群?
- reactjs - 真实项目的纯 mobx(无 MST)存储模型
- docker - Docker - 运行容器时清理文件内容
- javascript - 如何在javascript中将时间转换为用户本地时区