※大家来找茬!看看你能从代码中找到哪些缺点!! ※

[复制链接]
查看11 | 回复1 | 2021-1-27 06:45:37 | 显示全部楼层 |阅读模式
各位大神们好。想让大家看一下一段小代码,然后请指摘出这个代码都有哪些缺点,应该如何改善。无论从理论上代码运行速度的缺点也好,还是从程序美观方面来说,有任何缺点都请试着提出。
程序目的:指定任何格式文件,将这个文件中所有内容以字节为单位倒着输入进另一新建立的文件中。(源文件内容0x12,0x32,0xFF;新文件内容0xFF,0x32,0x12)
当新文件(默认为C:/test.txt)成功建立后,进入下一个环节:手动输入任何内容,将在新文件中进行检索。如果找到这个内容,则将提示该内容在新文件的什么位置(开头开始数第几个字节)。
代码如下
#include
#include
#include
usingnamespacestd;
#defineLNAME""
#defineNEW_FILE_NAME"C:/newfile.txt"
voidsearch(char*key);
intfind(FILE*p_file,char*pStr);
intmain()
{
//下面是通过输入文件名与位置寻找文件部分
inti;
intlen;
charfile_name[50];
charload_location[50]=LNAME;
printf("theoutputfilenewfile.txtwillbeinyourCdisk\n");
printf("Enterthefulladdressofthefileyouwannainput,includingfileExtension\n(forexampleC:/test.txt):\n");
fflush(stdin);
fgets(file_name,sizeof(file_name),stdin);
len=strlen(file_name);
if(file_name[len-1]=='\n')
file_name[len-1]=0;
strcat(load_location,file_name);
FILE*pfile_forread=fopen(load_location,"r");
FILE*pfile_forwrite=fopen(NEW_FILE_NAME,"w");
//找文件到此为止

if(!pfile_forread||!pfile_forwrite)
{
printf("thefileyouarelookingfordoesn'texist");
intinputanykey1;
inputanykey1=getchar();
return1;
}
intindex=1;
while(!fseek(pfile_forread,-index,SEEK_END))
{
chardata;
if(fread(&data,1,1,pfile_forread))//按字节读取文件内容
{
fwrite(&data,1,1,pfile_forwrite);//同时按字节将文件内容输入进新文件
}
if(!ftell(pfile_forread))//文件指针越界的话跳出
{break;}
index++;
}
fclose(pfile_forread);
fclose(pfile_forwrite);
while(1)
{chars[50];
printf("\ninputthedatayouarelookingforintheoutputfile\n");
cin>>s;
search(s);//!!!!!!!!!********************************输入要寻找的文件内容********************************************!!!!!!!!!!!!!!
}
intinputanykey2;
inputanykey2=getchar();
inputanykey2=getchar();
return0;
}

voidsearch(char*key)//如果在文件中找到了所寻内容的第一个字节,则search函数就在这里调用find函数来确定到底这里是不是所寻找的内容
{
FILE*pfile_read=fopen(NEW_FILE_NAME,"r");
if(!pfile_read)
{printf("failedtoopenfile\n");}
charbuffer;
intiPos;
charchar_arr[1000];
strcpy(char_arr,key);
while(fread(&buffer,1,1,pfile_read))
{
if(buffer==char_arr[0])
{
if(iPos=find(pfile_read,char_arr))
printf("Specifieddatafoundatoffset%d\n",iPos-1);
}
}
}

intfind(FILE*p_file,char*pStr)//find函数是在所寻内容的第一个字节找到后判断那之后的内容与所寻内容是否相同的                                          
{
intiPos=ftell(p_file);                            
charchBuff;
intfpos;        
for(pStr++;fpos=fread(&chBuff,1,1,p_file)&&*pStr;++pStr)//なぜ"++pStr"ですか? もし文字配列の範囲を超えると、もうforループ中のプロセスを進行する必要はないからです。
{
if(*pStr!=chBuff)//将文件内容与所寻内容一个个字节的比较
{
fseek(p_file,iPos,SEEK_SET);// 如果那里并不是所寻内容,则指针归位 
return0;
}
}
if(!(*pStr))/
{
returniPos;
}
if(fpos==0)
{
fseek(p_file,iPos,SEEK_SET);
return0;
}
}

分 -->
回复

使用道具 举报

千问 | 2021-1-27 06:45:37 | 显示全部楼层
自己顶一顶~~~呵呵~~~小朋友们快来看哦
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行