【问题标题】:Simple program leads to seg fault when opening a file简单程序在打开文件时导致 seg 错误
【发布时间】: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


【解决方案1】:

您应该使用argc(给定参数的数量)来确定是否输入了值。就目前而言,当argc0 时访问argv[1],将导致分段错误当您访问通过数组末尾时strcmp 取消引用终止NULL指针。

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

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

【讨论】:

  • 实际上这并不完全正确。 argv[] 数组总是有一个最终的 NULL 指针条目。实际问题是试图取消引用该 NULL 指针以与“test.txt”进行比较。正如您所说,修复方法是检查 argc 是否 >1,以确保有一个有效值可供检查。
  • @user362949 谢谢,更新了我的答案。我已经有一段时间没有做过任何 C 编程了。
【解决方案2】:

当您将参数传递给 main() 时,它们会以字符串的形式传递给 main()。 argc 是传递给 main() 的参数的计数,而 argv 是始终以 NULL 结尾的参数向量。所以如果你不提供任何参数,你必须先检查 argc count 然后继续。另一件事是您无法检查是否仅在一种情况下传递了错误的文件名或根本没有传递文件名

应该是这样的,

int main (int argc, char * argv[])
{
    FILE * ptr;
    if(argc>1)
    {
        if(strcmp(argv[1],"test.txt") == 0)
        {
            printf("Right text file was inputted");
        }
        else
        {
            printf("You didn't enter the right textfile");
            exit(1);
        }
    }
    else
        printf("you havn't entered any file name");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    相关资源
    最近更新 更多