c - 简单的程序在打开文件时导致段错误

标签 c file printing segmentation-fault arguments

我有一个包含一堆字符串的文本文件,对于我的问题来说没有什么重要的。

这里的代码编译/运行,如果我输入正确的文本文件,第一个 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(给出的参数数量的计数)来确定是否输入了值。就目前情况而言,当 argc0 时访问 argv[1] 将导致段错误 ,因为您访问的参数已传递给当 strcmp 取消引用终止 NULL 指针时,数组的末尾

您的第一个 if 语句应该是:

if(argc > 1 && strcmp(argv[1],"test.txt") == 0) {
...

关于c - 简单的程序在打开文件时导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977670/

相关文章:

c++ - 距离 Windows 挂起的剩余时间

windows - 如何将尖括号等特殊字符输出到 HTML/XHTML/XML 文件中?

C 使用 fstat() 读取文件大小

html - 从网页打印信封

java - java中的ESC/POS图像

c - 如何通过 Eclipse 使用 C 写入 txt 文件(通过控制台输入)

c++ - 英语和希腊语 UTF 字符差异

c++ - 按行解析和排序 csv 文件

c++ - 二进制字符串向后打印

c - 使用指向外部结构元素的指针进行静态数组初始化?