【发布时间】:2015-03-11 02:40:28
【问题描述】:
我有一个包含一堆字符串的文本文件,就我的问题而言,这并不重要。
这里的代码编译/运行,如果我输入正确的文本文件,第一个 if 语句就会运行。但是,如果我不执行 else 语句,而是出现 seg 错误,那么 Mallocing 指针在这里会有帮助吗?任何帮助将不胜感激。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main (int argc, char * argv[])
{
FILE * ptr;
if(strcmp(argv[1],"test.txt") == 0)
{
printf("Right text file was inputted");
}
//but if I wan't the alternative (if the user didn't enter the right thing
else
{
// this never executes, but instead the program just seg faults if the first if statement is not true
printf("You didn't enter the right textfile, or none at all");
exit(1);
}
}
【问题讨论】:
-
你根本没有访问
ptr。 -
"you don't" 表示您没有输入任何文件名作为参数,或者只是输入了错误的文件名?我猜你没有输入任何文件名,所以出现了索引超出范围的问题。你应该首先检查 argc 然后 argv
-
这段代码编译不干净有(至少)两个原因。 1)未使用传递的参数'argc'。 2) 这个函数被声明为返回一个 int,但实际上并没有这样做。 (它需要 'return(0);' 在最后关闭 '}' 之前。
标签: c file printing segmentation-fault arguments