0

I'm new to c programming. I'd like to use a function inside a switch or if else statement. But after I run the program. It immediately show me segmentation fault and exit the program. Below is my code. Please run through it

void phone1();
int main()
{
    int option;
    while (1) {
        printf("1) Option 1 \n");
        printf("2) Option 2 \n");
        scanf("%d", &option);
        switch (option) {
        case 1:
            phone1();
            break;
        case2:
            phone2();
            break;
        default:
            printf("Error");
            break;
        }
        while (1);
        return 0;
    }
}

void phone1()
{
    FILE* fi;
    char value[100];
    fi = fopen("phone.txt", "r");
    fseek(fi, -10, SEEK_END);
    fgets(value, 100, fi);
    printf("%s", value);
    fclose(fi);
}

And here is my phone.txt file

phone1 John 192901
phone2 Joseph 858201
phone3 Jay 757279
phone4 Teddy 847291
phone5 Ed 469274

I tried the function outside switch statement inside int main() and everything works fine. So I don't know what cause the segmentation fault to fail within the switch statement.

4

1 回答 1

2

首先,您需要为while循环块添加一个右大括号,并在最后省略那个。

其次,你不应该fseek()消极。你试图达到什么目的?

您的函数打开一个文件,并将前 100 个字符读入 value。然后,它打印它们。我想我在这里得到了你想要达到的目标,所以这是我大致如何做的一个例子。

#include <stdio.h>

int main()
{   
    FILE *fptr = fopen("contacts.txt", "r");
    int contact;
    char name[100]; // or whatever size you need
    int number;
    char c = 'a';
    scanf("%d", &contact);
    ++contact; // to use 1-based numbering
    for (int i = 0; i < contact && c != EOF; ++i)
        while ((c = fgetc(fptr)) != EOF && c != '\n');
    // safely jumps to contact-th line
    fscanf(fptr, "%s %d", name, &number);
    printf("%s\t%d\n", name, number);
    return 0;
} 

这需要一个contacts.txt形式:

Ed 1234
Emma 7890

您还可以让它检查有多少联系人条目/行,并绑定检查输入。

于 2020-12-22T07:08:30.197 回答