我有一个包含一堆字符串的文本文件,对于我的问题来说没有什么重要的。
这里的代码编译/运行,如果我输入正确的文本文件,第一个 if 语句就会运行。但是,如果我不执行 else 语句,而是出现段错误,那么 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);
}
}
最佳答案
您应该使用argc
(给出的参数数量的计数)来确定是否输入了值。就目前情况而言,当 argc
为 0
时访问 argv[1]
将导致段错误 ,因为您访问的参数已传递给当 。strcmp
取消引用终止 NULL
指针时,数组的末尾
您的第一个 if
语句应该是:
if(argc > 1 && strcmp(argv[1],"test.txt") == 0) {
...
关于c - 简单的程序在打开文件时导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977670/