用c语言将第一个单词保存到文件中
这部分代码有一个问题,我试图读取文件的行,只剪切每行的第一个字,然后将其保存在数组中 示例: 两条路在一片黄色的树林中分叉 很抱歉我不能同时旅行 当一个旅行者,我站了很久 我尽可能地往下看了一眼 它在灌木丛中弯曲的地方 因此,我期望得到这样一个向量:“2,and,and,to” 但我明白了:“去,去,去,去,去” 我的代码用c语言将第一个单词保存到文件中,c,C,这部分代码有一个问题,我试图读取文件的行,只剪切每行的第一个字,然后将其保存在数组中 示例: 两条路在一片黄色的树林中分叉 很抱歉我不能同时旅行 当一个旅行者,我站了很久 我尽可能地往下看了一眼 它在灌木丛中弯曲的地方 因此,我期望得到这样一个向量:“2,and,and,to” 但我明白了:“去,去,去,去,去” 我的代码 dictionary *load_word(int autor, dictionary *D_first) { FILE *date; char line[LONG_
dictionary *load_word(int autor, dictionary *D_first)
{
FILE *date;
char line[LONG_MAX_LINE];
char exeption[4] = " \n\t";
char *word;
int j=0;
if (autor == 1)
{
if ((date = fopen("test.txt", "r")) == NULL)
{
perror("robert_frost.txt");
}
while (fgets(line, LONG_MAX_LINE, date ) != NULL)
{
word = strtok(line, exeption); /*first word*/
add_dictionary_first(D_first, j, word);
j++;
}
fclose(date);
}
return D_first;
}
void add_dictionary_first(dictionary *D, int cont, const char *value)
{
expand_dictionary(&D, 1);
D->Distribution[D->size-1]->cont = cont;
D->Distribution[D->size-1]->value = value;
}
问题就在这条线上(莫斯科的弗拉德在评论中写道): 这只是指针赋值。这本身并没有错,但取决于 上下文,它不是你想要的
while (fgets(line, LONG_MAX_LINE, date ) != NULL)
{
word = strtok(line, exeption); /*first word*/
add_dictionary_first(D_first, j, word);
...
}
在这里,您首先调用add\u dictionary\u
始终使用相同的变量行
。它是
数组,但当数组作为参数传递给
功能。这意味着所有的D->Distribution[D->size-1]->值都指向
同一地点。输入文件中的最后一行以到
开头,这就是为什么只有
至
您需要使用strcpy
复制字符串
男式strcpy
选项2
如果系统中有可用的strdup
D->Distribution[D->size-1]->value = strdup(value);
if(D->Distribution[D->size-1]->value == NULL)
{
// error handling
}
在任何一种情况下,您都必须稍后释放内存。首先添加字典可能有问题。?@uan J.Mart指针单词指向同一个本地数组单词=strtok(行,例外);首先向我们显示您的
add\u dictionary\u
指针单词指向同一本地数组word=strtok(line,exeption)
yes,但是strtok
也会修改缓冲区,将\0
放在第一个令牌的末尾。这取决于add\u dictionary\u如何首先
复制单词,如果它只是一个指针赋值,那么这是一个问题,它需要执行一个strcpy
已添加的函数。
#include <string.h>
char *strcpy(char *dest, const char *src);
D->Distribution[D->size-1]->value = malloc(strlen(value) + 1); // note the +1 here
if(D->Distribution[D->size-1]->value == NULL)
{
// error handling
}
strcpy(D->Distribution[D->size-1]->value, value);
D->Distribution[D->size-1]->value = strdup(value);
if(D->Distribution[D->size-1]->value == NULL)
{
// error handling
}