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



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

所以我想把"编码"这个词存储到数组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]='';
            if(d==EOF)
                 break;
            d=fgetc(q);
         }

如果你不是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 spacen");
myword[i]=''; // Null terminating the string
printf("String from file %sn",myword);
fclose(ptr);

最新更新