[英]read line from file and store each word into an array (C language)
I'm trying to make a function in C that reads a first line form file and store each word into an array of strings, than return the array or print it (I used strtok()). 我试图在C中创建一个函数,该函数读取第一个行格式文件并将每个单词存储到字符串数组中,而不是返回该数组或将其打印出来(我使用strtok())。 I've written my code but when I test it I get an error: "segmentation error" which I don't know what it means.
我已经编写了代码,但是在测试时我得到一个错误:“分段错误”,我不知道它是什么意思。 any help???
任何帮助??? I saw this question Segmentation fault with array of strings C i think it's similar but I still don't understand.
我看到了这个问题,它用字符串C的数组分割错误,我认为这是相似的,但我仍然不明白。 Here's my code :
这是我的代码:
the function that reads data from file and store it into an array function is on the file: methodes.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);
}
and here's the main.c // I pass the file as argument (in argv) 这是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;
}
and here's an example of the file : methodes.txt 这是文件的示例:methodes.txt
afficher tableau
partager elements roles
nommer type profession
fin
and this is my output: 这是我的输出:
file opened
Erreur de segmentation
note: the output is in french, so the message means segmentation error thank you and sorry for all the details, i just wanted to make sure that people understand what i mean. 注意:输出为法语,因此该消息表示细分错误,非常感谢,并为所有详细信息感到抱歉,我只是想确保人们理解我的意思。
char ** tab;
Is a uninitialised pointer to a pointer. 是指向指针的未初始化指针。 What you need is a array of pointers.
您需要的是一个指针数组。
char *tab[10];
Instead of 10, use the size you see fit and adjust your code to include bounds checking. 而不是10,使用您认为合适的大小并调整代码以包括边界检查。
http://www.tutorialspoint.com/cprogramming/c_array_of_pointers.htm http://www.tutorialspoint.com/cprogramming/c_array_of_pointers.htm
pointer of an array: 数组的指针:
int *ptr[MAX];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.