[英]how to store words from a file to a dynamic array of strings?
I'm trying to store data from a file (words line by line) maximum length is 16我正在尝试存储文件中的数据(逐行单词)最大长度为 16
when I run the code it only stores the last word on the file and prints it (number of all the words in the file) times.当我运行代码时,它只存储文件中的最后一个单词并打印它(文件中所有单词的数量)次。
if the file contains 10 words and the last word is test, the output is test 10 times如果文件包含 10 个单词,最后一个单词是 test,则 output 被测试 10 次
when I tried while loop to scan the file I got garbage data当我尝试 while 循环扫描文件时,我得到了垃圾数据
here is my code这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *file;
file = fopen("words.txt", "r");
char word[20];
int words_count=0; // count the words in the file
while (fscanf(file, "%s", word) != EOF)
{
words_count++;
}
printf("%d", words_count); // i get the right number of words in the file at this step
char **list_of_words = malloc (words_count * sizeof(char *)); //allocate memory to store enough pointers to charecters
int length;
for (int i=0; i<words_count; i++)
{
fscanf(file, "%s", word);
length = strlen(word);
word[length+1] = '\0';
list_of_words[i] = malloc (length+1 * sizeof(char)); //allocate memory for each word
list_of_words[i] = word; //I used strcpy(), but I got the same output
}
for (int i=0; i<words_count; i++)
{
printf("%s\n", list_of_words[i]); //print the words
}
fclose(file);
}
There are several issues:有几个问题:
strcpy
here, list_of_words[i] = word
is pointless, you want to copy the string, not overwrite the previously allocated pointer with a pointer to a local variable (try it and see what happens).strcpy
, list_of_words[i] = word
是没有意义的,你想要复制字符串,而不是用指向局部变量的指针覆盖之前分配的指针(试试看会发生什么)。length+1 * sizeof(char)
is wrong, you intended (length + 1) * sizeof(char)
. length+1 * sizeof(char)
是错误的,您打算(length + 1) * sizeof(char)
。 However by chance both expressions give the same result.length+1
is enough because sizeof(char)
is 1 by definition.length+1
就足够了,因为sizeof(char)
根据定义为 1。word[lengt+1] = '\0'
is useless because after fscanf
word[length+1]
is 0 by definition. word[lengt+1] = '\0'
是无用的,因为在fscanf
之后word[length+1]
根据定义为 0。 But it doesn't cause a bug. ...
fseek(file, SEEK_SET, 0); // rewind the file so you can read it
// again
for (int i = 0; i < words_count; i++)
{
fscanf(file, "%s", word);
length = strlen(word);
// word[length + 1] = '\0'; // remove this, it's useless
list_of_words[i] = malloc(length + 1); // remove the sizeof(char) which is 1 by definition
strcpy(list_of_words[i], word); // use strcpy
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.