首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

C语言中打开文件并查找的有关问题

2012-04-22 
C语言中打开文件并查找的问题以下程序段的目的是:打开文件“姓名列表.txt”,通过键盘输入一个姓名,并在里面

C语言中打开文件并查找的问题

以下程序段的目的是:打开文件“姓名列表.txt”,通过键盘输入一个姓名,并在里面查找是否存在该姓名
可是修改运行时老是不对!请各位朋友们帮忙改改,要是有其它更好的方法推荐一下也行
假设“姓名列表.txt”中的内容都是连续的(就是没有用任何符号隔开的),例如:李小龙赵本上马致远...

C/C++ code
#include <stdio.h>#include <string.h>int main(){    FILE *fp;    char str1[20],str2[20];    fp=fopen("姓名列表.txt","r");    printf("请输入要查找的姓名:");    scanf("%6s",str1);//输入3个以内的汉字作为姓名,不足的用空格补上    fscanf(fp,"%6s",str2);//3个3个的把汉字取出    while(!feof(fp)||(strcmp(str1,str2)!=0))    {        // fscanf(fp,"%6s",str2);      }    if(feof(fp))        printf("查找失败!在姓名列表中没有找到%s!\n",str1);    if(strcmp(str1,str2)==0)        printf("查找成功!在姓名列表中找到%s了!\n",str1);    return 0;}


[解决办法]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 100

int main(int argv, char **arg){
if(argv == 1 || argv>2){
printf("Usage: %s filename\n",arg[0]);
exit(1);
}
FILE *fp = NULL;
if((fp=fopen(arg[1], "rt")) == NULL){
printf("open file erro\n");
exit(0);
}

char ch[MAXSIZE];
char find[MAXSIZE];
gets(find);
printf("inpurt find name=%s\n",find);
while(!feof(fp)){
fgets(ch, sizeof(ch), fp);
if(strstr(ch, find)){
printf("input name is in file\n");
}else{
printf("input name is not in file");
}
}

close(fp);

return 1;
}

[解决办法]
探讨
引用:

刚犯了低级错误。这样:
C/C++ code

#include <stdio.h>
#include <string.h>
char *get(FILE *fp)
{
fseek(fp,0,SEEK_END);
long len=ftell(fp);
char *src=(char*)malloc(len+1);
long beg=0;
fse……

热点排行