在外部文件的最后一行出现 fgets() 和分段错误的问题
Having an issues with fgets() and segmentation faults on last line of external file
这是我程序中的一段代码,它导致最后一行出现分段错误。我的程序应该从文件(如果用户指定)或控制台的手动输入中获取输入。当用户通过控制台输入句子时,它就起作用了。但是,当我从外部文件中获取句子时,我在最后一行(完成时将到达 EOF 的行)出现分段错误。 假设文件已关闭,并且在此代码段之外释放了内存。
这是片段:
if(inputExists == 1) {
char *input = malloc(256);
ip = fopen(inFile, "r");
if(ip) {
while(fgets(input, 256, ip) != NULL) {
printf("%s", input);
}
}
}
这是外部文件中的内容:
bob is working.
david is a new hire.
alice is bob's boss.
charles doesn't like bob.
这是完整程序(其中选择了用户从外部文件输入的选项)时我得到的输出。
bob is working.
david is a new hire.
alice is bob's boss.
Segmentation fault
如果您认为需要更多代码来找到问题,请告诉我,我会添加完整的程序(尽管老实说它非常丑陋和混乱)。
存在多个问题。首先,free
已分配内存。
free(input);
此外,文件需要关闭。
fclose(ip)
好的,我发现问题出在哪里了。我的指针 malloc'd 在循环之外,它从输入文件接收字符序列。因此,它一遍又一遍地引用相同的位置……显然,当我尝试引用多行代码时,这会导致问题,因为 *input 变量仅指向代码的最后一行.当我把它改成这个时:
else if(inputExists == 1) {
//First open the file
inputFile = fopen(inFile, "r");
//If said file exists
if(inputFile) {
while(!feof(inputFile)) {
char *temp2 = malloc(500);
fgets(temp2, 500, inputFile);
if((strlen(temp2)>0) && (temp2[strlen (temp2) - 1] == '\n')) {
temp2[strlen (temp2) - 1] = '[=10=]';
}
root = insert(root, temp2);
}
}else {
printf("The file/directory you specified does not exist or won't open.\n");
}
fclose(inputFile);
}
代码有效。感谢 guys/gals 的帮助,非常感谢,我学到了很多关于指针和 fgets
的知识
这是我程序中的一段代码,它导致最后一行出现分段错误。我的程序应该从文件(如果用户指定)或控制台的手动输入中获取输入。当用户通过控制台输入句子时,它就起作用了。但是,当我从外部文件中获取句子时,我在最后一行(完成时将到达 EOF 的行)出现分段错误。 假设文件已关闭,并且在此代码段之外释放了内存。
这是片段:
if(inputExists == 1) {
char *input = malloc(256);
ip = fopen(inFile, "r");
if(ip) {
while(fgets(input, 256, ip) != NULL) {
printf("%s", input);
}
}
}
这是外部文件中的内容:
bob is working.
david is a new hire.
alice is bob's boss.
charles doesn't like bob.
这是完整程序(其中选择了用户从外部文件输入的选项)时我得到的输出。
bob is working.
david is a new hire.
alice is bob's boss.
Segmentation fault
如果您认为需要更多代码来找到问题,请告诉我,我会添加完整的程序(尽管老实说它非常丑陋和混乱)。
存在多个问题。首先,free
已分配内存。
free(input);
此外,文件需要关闭。
fclose(ip)
好的,我发现问题出在哪里了。我的指针 malloc'd 在循环之外,它从输入文件接收字符序列。因此,它一遍又一遍地引用相同的位置……显然,当我尝试引用多行代码时,这会导致问题,因为 *input 变量仅指向代码的最后一行.当我把它改成这个时:
else if(inputExists == 1) {
//First open the file
inputFile = fopen(inFile, "r");
//If said file exists
if(inputFile) {
while(!feof(inputFile)) {
char *temp2 = malloc(500);
fgets(temp2, 500, inputFile);
if((strlen(temp2)>0) && (temp2[strlen (temp2) - 1] == '\n')) {
temp2[strlen (temp2) - 1] = '[=10=]';
}
root = insert(root, temp2);
}
}else {
printf("The file/directory you specified does not exist or won't open.\n");
}
fclose(inputFile);
}
代码有效。感谢 guys/gals 的帮助,非常感谢,我学到了很多关于指针和 fgets
的知识