从文本文件读取程序尝试在文件完成后读取额外的行

时间:2018-06-06 06:54:02

标签: c file

我正在开发一个程序,它假定从文本文件中读取信息。在this question的帮助下,我当时能够读到1行。现在我写了一个循环,它通过文件运行并读取所有内容:

int main(void)
{
    FILE * fp;
    fp = open_file("test.txt");
    while(1){
        if(feof(fp))
            break;
        product_t * product = read_line(fp);
        print_product(product);
    }
    fclose(fp);
    return(0);
}

以下是我用来从文本文件中读取的整个程序:https://pastebin.com/pe1XZj7c

我正在尝试阅读的文件如下所示:

H235 Sportello_dx N246 15:20:43 15:27:55
K542 Sportello_sx N247 10:03:10 10:15:30
A356 Maniglia_fronte G102 18:40:11 18:52:23

程序读取整个文件并正确处理数据,但后来出现了分段错误。以下是整个计划的输出:

product_t code_product: H235 
product_t name: Sportello_dx 
product_t code_piece: N246 
product_t enter: 15:20:43 
product_t exit: 15:27:55 
product_t code_product: K542 
product_t name: Sportello_sx 
product_t code_piece: N247 
product_t enter: 10:3:10 
product_t exit: 10:15:30 
product_t code_product: A356 
product_t name: Maniglia_fronte 
product_t code_piece: G102 
product_t enter: 18:40:11 
product_t exit: 18:52:23 
Segmentation fault

我使用GDB试图找出导致分段错误的原因。这是它给我的输出,包括回溯:

Starting program: /home/trie/Desktop/Progett Asd/a.out 
product_t code_product: H235 
product_t name: Sportello_dx 
product_t code_piece: N246 
product_t enter: 15:20:43 
product_t exit: 15:27:55 
product_t code_product: K542 
product_t name: Sportello_sx 
product_t code_piece: N247 
product_t enter: 10:3:10 
product_t exit: 10:15:30 
product_t code_product: A356 
product_t name: Maniglia_fronte 
product_t code_piece: G102 
product_t enter: 18:40:11 
product_t exit: 18:52:23 

Program received signal SIGSEGV, Segmentation fault.
__GI_____strtol_l_internal (nptr=0x0, endptr=endptr@entry=0x0, 
    base=base@entry=10, group=group@entry=0, 
    loc=0x7ffff7dd4400 <_nl_global_locale>) at ../stdlib/strtol_l.c:293
293 ../stdlib/strtol_l.c: No such file or directory.
(gdb) backtrace
#0  __GI_____strtol_l_internal (nptr=0x0, endptr=endptr@entry=0x0, 
    base=base@entry=10, group=group@entry=0, 
    loc=0x7ffff7dd4400 <_nl_global_locale>) at ../stdlib/strtol_l.c:293
#1  0x00007ffff7a70c82 in __strtol (nptr=<optimized out>, 
    endptr=endptr@entry=0x0, base=base@entry=10) at ../stdlib/strtol.c:106
#2  0x00007ffff7a6e290 in atoi (nptr=<optimized out>) at atoi.c:27
#3  0x0000555555554b5b in timestring_to_time (timestring=0x5555557589ea "18")
    at assembly_line_manager.c:106
#4  0x0000555555554a95 in read_line (fp=0x555555757010)
    at assembly_line_manager.c:82
#5  0x0000555555554924 in main () at assembly_line_manager.c:38

似乎程序试图在从文件中读取所有bean之后使用无效数据调用atoi函数。它为什么这样做?我怎么能阻止它?

0 个答案:

没有答案