簡體   English   中英

為什么我出現段錯誤(strcmp或fgets)?

[英]Why am I getting a seg fault (strcmp or fgets)?

我不明白為什么這么少的代碼會導致段錯誤。 我不知道這是strcmp還是fgets引起了問題。 我已經為此工作了兩天,請原諒我的無奈。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{

FILE* input;
char line[40];


    printf("%s\n", argv[1]);
    if ((strcmp(argv[1], "-f")) == 1)
    {           
        printf("Inside first if statement\n");          
        input = fopen(argv[2], "r");
        if(input == NULL)           
        {
            printf("Could not open file\n");
            exit(-1);
        }
    }
    while ((fgets(line, 40, input)) != NULL)
        {
        //printf("%s\n", input_line);
        }

return 0;
}
if ((strcmp(argv[1], "-f")) == 1)

應該:

if (strcmp(argv[1], "-f") == 0)

...您可能想先閱讀文檔。 參見strcmpfgets

您可能需要執行以下操作:

  • 檢查參數數量
  • 在line []中為NULL終止符分配空間
  • 成功時,strcmp返回= 0,> 0的不匹配位置
  • perl具有“ chomp”,您可以復制它以刪除多余的“ \\ n”

這是您的代碼,經過修改並可以正常使用,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int usage()
{
    printf("usage: %s -f <file>\n",argv[0]);
}

int main(int argc, char* argv[])
{
    FILE* input;
    char line[+1]; //allow room for NULL terminator

    if (argc < 3 || strcmp(argv[1], "-f") ) { usage(); exit(1); }
    printf("file: %s\n", argv[2]);
    if( (input = fopen(argv[2], "r")) == NULL)
    {
        printf("open %s\n",argv[2]);
        exit(2);
    }
    //ask C how big line[] is
    while ( fgets(line, sizeof(line), input) != NULL )
    {
        //line[sizeof(line)-1] = '\0'; //fgets does this for us
        printf("%s\n", line);
    }
    return 0;
}

順便說一句:*使用EXIT_SUCCESS和EXIT_FAILURE(對於非UNIX環境)比使用0和一些非零值(例如1或-1)更容易移植。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM