Хранение информации из файла в структуре на C - в результате ошибки сегментации - PullRequest
0 голосов
/ 16 июня 2019

Я пишу программу для хранения информации из входного файла и распечатки информации по выбору пользователя. Я еще не дошел до части выбора использования, но сразу столкнулся с ошибкой сегментации. Я знаю, что это означает, что я пытаюсь получить доступ к местам в памяти, которые либо не существуют, либо недоступны.

Я не уверен в том, что я делаю неправильно. Я пытаюсь сохранить информацию из входного файла в моей структуре.

Входной файл в этом формате

3
5 Name Name 10 56789
7 Name Name 7 67894
8 Name Name 10 89375

Я попытался получить доступ к структурам напрямую как emp [1] .id и т. Д. Вместо emp [i] .id и т. Д. Это тоже не сработало.

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

// structures
struct emp
{
    int id;
    char firstname[10];
    char lastname[10];
    int department;
    float salary;
} emp[10];


// function prototypes
// nothing here yet

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

int i = 0;
int choice;

if(argc != 2){

printf("Usage: %s input.txt\n", argv[0]);
exit(EXIT_FAILURE);
}

FILE* inputFile;


inputFile = fopen("input.txt", "r");

    if(inputFile == NULL){
            printf("Error opening %s\n", argv[1]);
            exit(EXIT_FAILURE);
    }
// file is open now

// loop to save information from file into structure

 int num;

    fscanf(inputFile, "%d", &num);


            for(i = 0; i < num; i++){
    fscanf(inputFile, "%d", emp[i].id);
    fscanf(inputFile, "%s", emp[i].firstname);
    fscanf(inputFile, "%s", emp[i].lastname);
    fscanf(inputFile, "%d", emp[i].department);
    fscanf(inputFile, "%f", emp[i].salary);

}


    printf("\n");
    printf("Welcome to the Employee Database!\n");
    printf("---------------------------------\n");
    printf("Choose an option:\n");
    printf("1:   Print empid\n");
    printf("2:   Print ALL employees\n");
    printf("3:   Show ALL employees in department\n");
    printf("-1:  QUIT\n");
    scanf("%d", &choice);

// I have not set up the functions to perform the selection options yet 
return 0;
}

Это вывод, который я получаю.

c803@cs2:~A5$ gcc A5.c
c803@cs2:~A5$ ./a.out input.txt
Segmentation fault

1 Ответ

2 голосов
/ 16 июня 2019

Здесь fscanf берет адрес памяти переменных для хранения прочитанных данных, как и scanf ().Вам нужно поставить '&' перед emp [i] .id и всеми другими элементами данных, кроме символьных массивов, так как само имя массива дает адрес первых членов массива массива.Таким образом, код должен быть ::

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

// structures
struct emp
{
    int id;
    char firstname[10];
    char lastname[10];
    int department;
    float salary;
} emp[10];


// function prototypes
// nothing here yet

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

int i = 0;
int choice;

if(argc != 2){

printf("Usage: %s input.txt\n", argv[0]);
exit(EXIT_FAILURE);
}

FILE* inputFile;


inputFile = fopen("input.txt", "r");

    if(inputFile == NULL){
            printf("Error opening %s\n", argv[1]);
            exit(EXIT_FAILURE);
    }
// file is open now

// loop to save information from file into structure

 int num;

    fscanf(inputFile, "%d", &num);


            for(i = 0; i < num; i++){
    fscanf(inputFile, "%d", &emp[i].id);
    fscanf(inputFile, "%s", emp[i].firstname);
    fscanf(inputFile, "%s", emp[i].lastname);
    fscanf(inputFile, "%d", &emp[i].department);
    fscanf(inputFile, "%f", &emp[i].salary);

}


    printf("\n");
    printf("Welcome to the Employee Database!\n");
    printf("---------------------------------\n");
    printf("Choose an option:\n");
    printf("1:   Print empid\n");
    printf("2:   Print ALL employees\n");
    printf("3:   Show ALL employees in department\n");
    printf("-1:  QUIT\n");
    scanf("%d", &choice);

// I have not set up the functions to perform the selection options yet 
return 0;
}
...