#include <iostream>
using namespace std;
int size(char*path);//计算路径长度
char* filename(char*path);//获取文件名
char* filepath(char *path);//获取文件所在目录
char* refilecata(char*orig,char*now);//替换文件目录 orig是原来的文件路径,now是要替换成的目录
char* connect(char*cata,char*file);//连接文件目录和文件名
int main(){
char *path="c:\\program files\\data.txt";
return 0;
}
int size(char*path){
int cnt=0;
while(path[cnt]!='\0'){
cnt++;
}
return cnt;
}
char* filename(char*path){
int cnt=size(path)-1;
//从后往前查询
while(path[cnt]!='\\'){
cnt--; //最后一个'\'的位置 因为这个位置之后是文件名字
}
char *copy=(char*)malloc(size(path)-cnt);//开辟一片文件大小的指针
for(int i=cnt+1;i<size(path);i++){
copy[i-cnt-1]=path[i];//读取文件名字
}
copy[size(path)-cnt-1]='\0';//最后一位设置为 '\0'
return copy;
}
char* filepath(char *path){
int cnt=size(path)-1;//下标
while(path[cnt]!='\\'){
cnt--;//找到最后一个'\'
}
char*copy=(char*)malloc(cnt+2);
for(int i=0;i<=cnt;i++){
copy[i]=path[i];//读入
}
copy[cnt+1]='\0';
return copy;
}
char* refilecata(char*orig,char*now){//替换文件目录 orig是原来的文件路径,now是要替换成的目录
char* name=filename(orig);//找到文件的名字
int cnt1=size(name);//文件名长度
int cnt2=size(now); //被替换成的目录长度
char* copy=(char*)malloc(cnt1+cnt2+1);
for(int i=0;i<cnt2;i++){
copy[i]=now[i]; //读入目录
}
for(int i=0;i<cnt1;i++){
copy[i+cnt2]=name[i];//读入文件名
}
copy[cnt1+cnt2]='\0';
return copy;
}
char *connect(char*cata,char*file){
int cnt=size(cata)+size(file);
bool flag=0;
if(cata[size(cata)-1]!='\\'){
flag=1; //判断一下目录的最后一位是否为'\',并用flag标记一下
cnt++;
}
char*copy=(char*)malloc(cnt+1);
int jud=0;//数组下标
for(int i=0;i<size(cata);i++){
copy[jud++]=cata[i];
}
if(flag){
copy[jud++]='\\';//如果最后一位非'\',就加上
}
for(int i=0;i<size(file);i++){
copy[jud++]=file[i];
}
copy[jud]='\0';
return copy;
}
实验E4:对字符串的操作(函数接口设计、字符串操作)
于 2021-07-02 18:35:59 首次发布