【问题标题】:read line from file and store each word into an array (C language)从文件中读取行并将每个单词存储到一个数组中(C语言)
【发布时间】:2016-01-24 06:36:34
【问题描述】:

我正在尝试在 C 中创建一个函数,该函数读取第一行表单文件并将每个单词存储到字符串数组中,然后返回数组或打印它(我使用了 strtok())。我已经编写了我的代码,但是当我测试它时,我收到一个错误:“分段错误”,我不知道它是什么意思。 有什么帮助吗???我看到了这个问题Segmentation fault with array of strings 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

注意:输出是法语,所以消息表示分段错误 谢谢你,很抱歉所有的细节,我只是想确保人们理解我的意思。

【问题讨论】:

  • tab 未初始化(未分配内存)并使用了tab[i],因此出现分段错误。
  • 还有tab[i] = malloc(len);strncpy(tab[i], token, len-1);token = strtok(NULL, s); --> tab[i] = malloc(len+1); strcpy(tab[i], token);token = strtok(NULL, " \n");
  • @BLUEPIXY 我像这样更改了数组的初始化:char *tab[4],并且代码工作正常。但是当我尝试你在第二条评论中所说的内容时,它给了我一个编译错误:函数的参数太少 \u2018strncpy\u2019 strncpy(tab[i], token);
  • 你有错字 strncpy as strcpy
  • @BLUEPIXY 是的,对不起。如果我可以问你另一个问题...我希望我的函数返回一个字符串数组,然后在 main 中使用它;我这样做了: char ** lireFichier(char *line) {....} 主要是: char *tab[4]; tab = lireFichier(line); (我更改了参数,将字符串而不是文件传递给函数)但这不起作用..

标签: c arrays file strtok


【解决方案1】:
 char ** tab;

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

char *tab[10];  

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

【讨论】:

  • 非常感谢你们的回答,现在我明白了我的错误,我只是改变了初始化数组的方式:char *tab[4];一切正常,就这么简单,但没注意。
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多