从文本文件中读取单词(一行中的单个单词)

时间:2016-07-22 04:31:51

标签: c

我在c中编写了以下代码来读取文本文件中的单词,但代码无效,请更正。 我有一个文件a.txt,其中:
编码

所以我希望将'Coding'这个词存储到数组b中。

q=fopen("a.txt","r");
d=fgetc(q);//q is pointer to text file
while(d!=EOF)
          {
            i=0;
            while((d!='\n')&&(d!=EOF));
            {  
                b[i++]=d;
                d=fgetc(q);
            }
            b[i]='\0';
            if(d==EOF)
                 break;
            d=fgetc(q);
         }

1 个答案:

答案 0 :(得分:0)

如果您没有malloc记忆,那么以下就是我的方法

int c; 
char myword[20]; // max characters to store is 20
int i=0;
FILE* ptr=fopen("38518211","r");
if (ptr==NULL){
printf("Can't open the file");
}
else{
while(i<19 && (c=fgetc(ptr)) != EOF)
  myword[i++]=c;
}
if((c=fgetc(ptr)) != EOF)
 printf("Original string is truncated to fit into alloted space\n");
myword[i]='\0'; // Null terminating the string
printf("String from file %s\n",myword);
fclose(ptr);
相关问题