2016-07-22 112 views
-4

我已经在c中编写了下面的代码来读取文本文件中的单词,但是代码不工作,请更正它。 我有一个文件a.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]='\0'; 
      if(d==EOF) 
       break; 
      d=fgetc(q); 
     } 
+1

问题寻求帮助调试(“为什么不是这个代码的工作?”)必须包括所期望的行为,一个特定的问题或错误以及在问题本身中重现它所需的最短代码 –

+0

@pcluddite代码是否正确? –

+2

如果它不像你说的那样工作,那么它可能不是。 –

回答

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); 
相关问题