【发布时间】:2020-09-07 20:55:30
【问题描述】:
我的问题是我需要从文件中读取字符串。文件示例:
示例 1 句
例句xd 595 xd 49 lol
但我必须只阅读字符串部分,而不是数字。我想我必须使用fscanf() 和%s,但请告诉我你们对此的看法。
我的问题开始的部分是如何使用malloc()、realloc() 读取字符串(长度未知)?我自己尝试过,但失败了(我的解决方案在我的帖子底部)。
然后我需要在屏幕上显示结果。
附:我必须使用malloc()/calloc(),realloc() char *)
我试过的代码:
int wordSize = 2;
char *word = (char *)malloc(wordSize*sizeof(char));
char ch;
FILE* InputWords = NULL;
InputWords = fopen(ListOfWords,"r"); /* variable ListOfWords contains name of the file */
if (InputWords == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
int index = 0;
while((ch = fgetc(InputWords)) != -1)
{
if(ch == ' ')
{
printf("%s\n", word);
wordSize = 2;
index = 0;
free(word);
char* word = (char *)malloc(wordSize*sizeof(char));
}
else
{
wordSize++;
word = (char *)realloc(word, wordSize*sizeof(char));
strcpy(word,ch);
index++;
}
}
fclose(InputWords);
【问题讨论】:
-
不相关的建议:使用
EOF(可以是任何负值)而不是-1 -
char ch:==>int ch;
标签: c string file pointers dynamic-memory-allocation