怎么样用C++读取文本文档里的数据,数据非常多,并且对之进行处理

VC读取txt文件内容,几乎全是数,
2024-12-25 10:40:01
推荐回答(4个)
回答1:

1. 从键盘输入单词,以“end”结束输入,把接收到的单词存入文件“word.txt”,
然后再编写一个函数void copyFileTo(File *p1,File *p2),
把word..txt中的单词复制到文件word2.txt中,并统计单词个数。

#include
#include
#include

void copyFileTo(FILE *p1,FILE *p2){
char ch;
ch = fgetc(p1);
while(ch != EOF){
fputc(ch,p2);
ch = fgetc(p1);
}

}
void main(){
FILE *fp,*fp2;
fp = fopen("word.txt","w");
char s[20];
scanf("%s",s);
while(strcmp(s,"end")!=0){
fprintf(fp,"%s ",s);
scanf("%s",s);
}
fclose(fp);
fp = fopen("word.txt","r");
fp2 = fopen("word2.txt","w");
copyFileTo(fp,fp2);
fclose(fp);
fclose(fp2);
}

2. 在题1的基础上,重写copyFileTo函数,void copyFileTo(File *p1,File *p2,char *s1,char *s2)
,文件p1中如果有单词s1,在存入文件2时改成s2。
#include
#include
#include

void copyFileTo(FILE *p1,FILE *p2,char *s1,char *s2){
char ch[20];

while(fscanf(p1,"%s",ch)==1){
if(strcmp(ch,s1)==0){
fprintf(p2,"%s ",s2);
}
else
fprintf(p2,"%s ",ch);
}

}
void main(){
FILE *fp,*fp2;
fp = fopen("word.txt","w");
char s[20];
scanf("%s",s);
while(strcmp(s,"end")!=0){
fprintf(fp,"%s ",s);
scanf("%s",s);
}
fclose(fp);
fp = fopen("word.txt","r");
fp2 = fopen("word2.txt","w");
copyFileTo(fp,fp2,"hello","world");
fclose(fp);
fclose(fp2);
}

3. 在题1的基础上,将单词按字母序排序,排序后存入文件sortedWords.txt中。

#include
#include
#include
#define M 30
#define N 20
void sortWords(FILE *p1,FILE *p2){
char ch[M][N];
char temp[N];
int i=0,j=0,k=0;
while(fscanf(p1,"%s",ch[i])==1){
//strcpy(ch[i],temp);
i++;
}
for(j=0;j for(k=j+1;k if(strcmp(ch[j],ch[k])==1){
strcpy(temp,ch[j]);
strcpy(ch[j],ch[k]);
strcpy(ch[k],temp);
}

for(j=0;j fprintf(p2,"%s ",ch[j]);
}

}
void main(){
FILE *fp,*fp2;
fp = fopen("word.txt","w");
char s[20];
scanf("%s",s);
while(strcmp(s,"end")!=0){
fprintf(fp,"%s ",s);
scanf("%s",s);
}
fclose(fp);
fp = fopen("word.txt","r");
fp2 = fopen("sortedWords.txt","w");
sortWords(fp,fp2);
fclose(fp);
fclose(fp2);
}

4. 一个文件中存有一串字母,把文件中字母‘a’改成‘b’。

#include
#include
#include

void main(){
FILE *fp,*fp2;
char ch;
fp = fopen("word.txt","r+");
ch = fgetc(fp);
while(ch != EOF){
if(ch=='a'){
fseek(fp,-1L,1);
fputc('b',fp);
fseek(fp,0L,1);
}
ch = fgetc(fp);
}

fclose(fp);

}

(附加题)
统计一个文件中的单词,显示单词和出现次数。
例如文件内容如下:
happy world happy life.

结果:
happy 2
world 1
life 1

#include
#include
#include
#define M 30
#define N 20

void countTimes(FILE *p1,FILE *p2){
char ch[M][N];
int times[M];
char temp[N];
int i=0,j=0,k=0;
for(j=0;j times[j] = 1;
while(fscanf(p1,"%s",temp)==1){
//strcpy(ch[i],temp);

for(k=0;k if(strcmp(ch[k],temp)==0)
break;
}
if(k times[k]++;
}
else{
strcpy(ch[i],temp);
i++;
}
}

for(j=0;j fprintf(p2,"%s %d\n",ch[j],times[j]);
}

}
void main(){
FILE *fp,*fp2;
fp = fopen("word.txt","w");
char s[20];
scanf("%s",s);
while(strcmp(s,"end")!=0){
fprintf(fp,"%s ",s);
scanf("%s",s);
}
fclose(fp);
fp = fopen("word.txt","r");
fp2= fopen("result.txt","w");
countTimes(fp,fp2);
fclose(fp);
}

以前写的绝对可以用

回答2:

时间和空间,通常只能节约一个,你要高效就得先把文件内容全部读入,并在读入时初步进行处理,比如按大小什么的

回答3:

用循环一个一个字节的读取啊。

回答4:

高效的方法得参考数据结构的查找这一方面的算法