我试图编写的代码应该读取txt文件中的文本并将其分离为字符串。我是来下面的代码:Strtok问题C(EOF字符?)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
FILE *fp;
int i=0;
char *words=NULL,*word=NULL,c;
if ((fp=fopen("monologue.txt","r"))==NULL){ /*Where monologue txt is a normal file with plain text*/
printf("Error Opening File\n");
exit(1);}
while ((c = fgetc(fp))!= EOF){
if (c=='\n'){ c = ' '; }
words = (char *)realloc(words, ++i*sizeof(char));
words[i-1]=c;}
word=strtok(words," ");
while(word!= NULL){
printf("%s\n",word);
word = strtok(NULL," ");}
exit(0);
}
的问题是,我得到的输出不仅是文本(现为独立的字符串),但也有一些字符是用\ r(这是回车),但也\ 241 \ r \ 002,我无法找出他们是什么?你能帮我吗?
是您的文件保存为Unicode? – Ulterior 2011-12-30 22:39:03
您可以为每个输入字符调用'realloc(),将缓冲区的大小增加1个字节。这可能是非常低效的。按需要加倍缓冲区大小会更快。你需要检查'realloc()'是成功还是失败。 – 2011-12-30 23:05:31