[英]Reading file word by word
I don't know why but my code prints a list of (null)(null)(null).... I have to print the list of words from a file 'words.txt'. 我不知道为什么,但是我的代码显示了(null)(null)(null)....的列表。我必须从文件'words.txt'中打印单词的列表。 Another question is: fscanf ignore white spaces?
另一个问题是:fscanf是否忽略空格?
#define WORD_LENGTH 1024
#define SIZE_QUOTE 100
int main(){
char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
long i;
for(i = 0; i < SIZE_QUOTE; i++){
if(!(malloc(sizeof(char) * (size_t)WORD_LENGTH)))
exit(1);
}
i = 0;
FILE *pf = fopen("words.txt", "r");
while(!feof(pf) && i < SIZE_QUOTE){
fscanf(pf, "%s", quote[i]);
printf("%s", quote[i]);
i++;
}
fclose(pf);
free(quote);
}
You're never assigning the return value of malloc()
to quote[i]
so they end up staying NULL
(if you're lucky): 您永远不会将
malloc()
的返回值分配给quote[i]
因此它们最终将保持为NULL
(如果幸运的话):
char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
long i;
for(i = 0; i < SIZE_QUOTE; i++){
if(!(malloc(sizeof(char) * WORD_LENGTH)))
It should be something like this instead: 应该是这样的:
char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
for(int i = 0; i < SIZE_QUOTE; i++){
quote[i] = malloc(sizeof(char) * WORD_LENGTH);
if(!quote[i])
Also you could avoid malloc()
entirely and statically initialize that array if all the sizes are known: 另外,如果所有大小都已知,则可以完全避免
malloc()
并静态初始化该数组:
char quote[SIZE_QUOTE][WORD_LENGTH] = {{'\0'}};
Also, you should be free()
-ing the individual quote[i]
at the end too: 另外,您还应该
free()
在末尾加上单个quote[i]
:
for(int i = 0; i < SIZE_QUOTE; ++i) free(quote[i]);
free(quote);
There's other mistakes that have been pointed out through the comments already, so I won't elaborate further. 注释中已经指出了其他错误,因此我不再赘述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.