繁体   English   中英

从文件中读取行并将每个单词存储到数组(C语言)中

[英]read line from file and store each word into an array (C language)

我试图在C中创建一个函数,该函数读取第一个行格式文件并将每个单词存储到字符串数组中,而不是返回该数组或将其打印出来(我使用strtok())。 我已经编写了代码,但是在测试时我得到一个错误:“分段错误”,我不知道它是什么意思。 任何帮助??? 我看到了这个问题用字符串C的数组分割错误,我认为这是相似的,但我仍然不明白。 这是我的代码:

从文件读取数据并将其存储到数组函数的函数在文件上:methodes.c

void lireFichier (char *file)
{
    int i = 0;
    int nbElement = 4;
    char ** tab;
    char line [1000];
    char *str[1000];
    const char s[2] = " ";
    char *token;
    FILE *myFile;

    myFile = fopen(file, "r");
    if(!myFile)
    {
        printf("could not open file");
    } else
    {
        printf("file opened\n");
        //while(fgets(line,sizeof line,myFile)!= NULL) 

        //get the fisrt line 
        fgets(line,sizeof line,myFile);

        //fprintf(stdout,"%s",line); 
        //get the fisrt word
        token = strtok(line, s);

        for(i =0; (i< nbElement) && (token != NULL); i++)
        {
            int len = strlen(token); 
            tab[i] = malloc(len);
            strncpy(tab[i], token, len-1);
            token = strtok(NULL, s);
            //printf( "%s\n", tab[i]);
        }   
    }
    fclose(myFile);
}

这是main.c //我将文件作为参数传递(在argv中)

#include <stdio.h>
#include <stdlib.h>
#include "methodes.h"


int main(int argc, char *argv[])
{
    int result = 1;
    if(argc < 2)
    {
        printf("Erreur dans les arguments\n");
    } else
    {
        int idx;
        for (idx = 0; idx < argc; idx++)
        {
            printf("parameter %d value is %s\n", idx, argv[idx]);
        }

       lireFichier(argv[1]);

    }
    return 0;
}

这是文件的示例:methodes.txt

afficher tableau
partager elements roles
nommer type profession
fin

这是我的输出:

file opened
Erreur de segmentation

注意:输出为法语,因此该消息表示细分错误,非常感谢,并为所有详细信息感到抱歉,我只是想确保人们理解我的意思。

 char ** tab;

是指向指针的未初始化指针。 您需要的是一个指针数组。

char *tab[10];  

而不是10,使用您认为合适的大小并调整代码以包括边界检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM