c - 读取文件时出现段错误(核心已转储)

标签 c string file segmentation-fault

我正在做一个简单的项目来读取 input.txt 文本文件并显示有关它的一些基本统计信息。该文件应该是关于公司大楼的入口。文件是这样的:

1 ; Visitor ; 10 ; 19 ; 2
2 ; 1 ; Worker ; 8 ; 0
3 ; 2 ; Director ; 12 ; 19
4 ; 5 ; Worker ; 18 ; 22
5 ; Visitor ; 8 ; 0 ; 3

Format is = ID ; Companions(if employee) ; Type ; Entrance Time ; Exit Time ; Services(if Visitor)

我让程序正确读取文件(我猜),它正确读取了第一个工作人员,但是当它到达第二个工作人员时,它读取了 ID 并突然退出并显示 Segmentation fault (core dumped).

example of error

如果有更多知识的人可以提供帮助,我将不胜感激,因为我不知道发生了什么,而其他具有相同错误的问题也没有帮助。

代码如下:

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef enum { false, true } bool;

char * removeSpaces(char *line) {
    int counter = 0,i=0;

    while (line[i]!='\0'){
        if (line[i] == ' '){
            i++;
        } else{
            line[counter] = line[i];
            counter++;
            i++;
        }
    }
    return(line);
    line[counter] = '\0';
}

int main (int argc, char *argv[]){
    FILE * fp;
    char * line = NULL;
    char field[30];
    size_t len = 0;
    ssize_t read;
    bool flag = false;
    int i=0,j=0,k=0,counter=0; //variables to count on loops

    fp = fopen("input.txt", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("%s", line);
        if(strstr(line, "Worker") != NULL) { //determine the entrance type
            line = removeSpaces(line);

            printf("\nWORKER READ\n");
            i = 0;
            while(line[i] != ';'){ //Read ID
                field[i] = line[i]; //saves the content of the field (all between ';')
                i++;
            }
            field[i] = '\0';
            printf("\nID: ");
            for(i=0;field[i] != '\0';i++){
                printf("%c",field[i]);
            }
            //memset(field,0,strlen(field));
            i = 0; j = 0;
            while(flag != true){ //Read Companions
                if(line[i] == ';'){
                    flag = true; //keeps skipping the string till it finds the right field
                }
                if(flag == true){
                    j = i+1;
                    while(line[j] != ';'){
                        field[k] = line[j]; //saves the content of the field (all between ';')
                        j++; k++;
                    }
                }
                i++;
            }
            field[k] = '\0';
            printf("\nCOMPANIONS: ");
            for(i=0;field[i] != '\0';i++){
                printf("%c",field[i]); //prints what the number of companions read
            }
            //memset(field,0,strlen(field));
            i = 0; j = 0; k = 0; flag = false;
            while(flag != true){ //Read Type
                if(line[i] == ';'){
                    counter++;
                    if(counter == 2){
                        flag = true; //keeps skipping the string till it finds the right field
                    }
                }
                if(flag == true){
                    j = i+1;
                    while(line[j] != ';'){
                        field[k] = line[j]; //saves the content of the field (all between ';')
                        j++; k++;
                    }
                }
                i++;
            }
            field[k] = '\0';
            printf("\nTIPO: ");
            for(i=0;field[i] != '\0';i++){
                printf("%c",field[i]); /prints the type of entrance read
            }
            //memset(field,0,strlen(field));
            i = 0; j = 0; k = 0;  flag = false; counter = 0;
            while(flag != true){ //Read Entrance Time
                if(line[i] == ';'){
                    counter++;
                    if(counter == 3){
                        flag = true; //keeps skipping the string till it finds the right field
                    }
                }
                if(flag == true){
                    j = i+1;
                    while(line[j] != ';'){
                        field[k] = line[j]; //saves it
                        j++; k++;
                    }
                }
                i++;
            }
            field[k] = '\0';
            printf("\nENTRANCE: ");
            for(i=0;field[i] != '\0';i++){
                printf("%c",field[i]);
            }
            i = 0; j = 0; k = 0;  flag = false; counter = 0;
            while(flag != true){ //Read Exit Time
                if(line[i] == ';'){
                    counter++;
                    if(counter == 4){
                        flag = true;
                    }
                }
                if(flag == true){
                    j = i+1;
                    while(line[j] != ';'){
                        field[k] = line[j];
                        j++; k++;
                    }
                }
                i++;
            }
            field[k] = '\0';
            printf("\nSAIDA: ");
            for(i=0;field[i] != '\0';i++){
                printf("%c",field[i]);
            }
            printf("\n\n");

            i = 0; j = 0; k = 0;  flag = false;
            memset(field,0,strlen(field));
        } else if(strstr(line, "Director") != NULL){
            //TODO
        } else if(strstr(line, "Visitor") != NULL){
            //TODO
        }
    }

    return 0;
}

最佳答案

虽然我建议使用 sscanffscanf 来编写复杂的解析代码,但学习如何编写解析器对您的编码技能也有好处。在调整你的代码以使用 fgets 而不是 getline 以便我可以编译它之后,我在这个循环中遇到了一个错误:

while ( flag != true )
{ //Read Type
    if ( line[i] == ';' ) // <<<< Fault when i = 2488
    {
        counter++;
        if ( counter == 2 )
        {
            flag = true; //keeps skipping the string till it finds the right field
        }
    }
    if ( flag == true )
    {
        j = i + 1;
        while ( line[j] != ';' )
        {
            field[k] = line[j]; //saves the content of the field (all between ';')
            j++; k++;
        }
    }
    i++;
}

您在不引用实际行的长度的情况下递增 i,因此在某些时候您正在访问不属于您的内存地址。

您应该在编译代码时启用所有警告。您的编译器应该警告您一些错误。您应该看到的重要内容之一是 removeSpaces 函数中第 27 行的“Unreachable code...”:

return(line);
line[counter] = '\0'; // This never executed.

参见 http://pubs.opengroup.org/onlinepubs/009696699/functions/fgets.html

关于c - 读取文件时出现段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117921/

相关文章:

c - fscanf 读取最后一个整数两次

c - 当编译到 gnu99 时,获取 "implicit declaration of function ' fcloseall' 在 C99 中无效”

file - 动态磁贴未从隔离存储中获取图像

c - 如何删除 "incompatible implicit declaration"警告

java - 在Java中查找字符串中所有出现的子字符串

string - 如何在haskell中组合两个字符串中的字母

java - 正则表达式在字母小写字符之后拆分大写字母

java - Java 中最简单的点对多点数据分发库/框架

c++ - 删除名称为使用字符串变量创建的文件

C 结构不扫描所有输入