读书人

解析ftp路径的有关问题

发布时间: 2012-02-11 09:51:34 作者: rapoo

解析ftp路径的问题
一字符串格式为 usr:pwd@ip:path/file 我想把他们截取出来 分为5部分
程序写好了 编译通过 但是结果有问题....谁能帮我看看?或者给个answer...
我猜可能是我一些函数没用好 strncpy memccpy 之类的

#include <cstdlib>
#include <iostream>
#include <tchar.h>
#include <ctime>

#include <stdio.h>
#include <string.h>


char* ExtractName( char *fullname)
{
char* usr;
char* pwd;
char* ip;
char* path;
char* file;
char* temp;
char* name;
int rpos = 0;
int lpos = 0;
name = fullname;
char* dest;

int at = -1;

for(int ii =strlen(fullname)-1; ((ii > 0) && (at < 0)); ii--) //get pos of '@'
{
if (fullname[ii] == '@')
{
at = ii;
}
}

int colon1 = -1;
//get the first colon betweet usr & pwd
for(int lpos = at-1; ((rpos > 0) && (colon1 < 0)); lpos--)
{
if(fullname[lpos] == ':')
{
colon1 = lpos;
// get string of usr & pwd
strncpy(usr,fullname,colon1-1);
usr[colon1] = '\0';
strchr(temp,':'); // string after first ':'
memccpy(pwd,temp,'@',at-lpos);


}
}

temp = strchr(temp, '@');//get the string after '@'

int colon2 = -1;

//get the second colon between ip & full path
for(int rpos = strlen(temp)-1; ((rpos > 0) && (colon2 < 0)); rpos--)
{
if(fullname[rpos] == ':')
{
colon2 = rpos;
strncpy(ip, temp, colon2-1);// get string of ip
ip[colon2] = '\0';
temp = strchr(temp, ':'); //get the string of 'fullpath'
}
}
int slash = -1;
for (int jj=strlen(temp)-1; ((jj > 0 ) && (slash < 0)) ; jj--)//the pos of last '/'
{
if(fullname[jj] == '/')
{
slash = jj;
strncpy(path, temp, slash); //get path
path[slash] = '\0';
file = strrchr(temp,'/');


}

}
std::cout << usr << endl
<< path << endl;
}

int main(int argc,char *argv[])
{
char* file1 = "kevin:pass@127.0.0.1:/var/path/kevin/demo.cpp" ;
char* s = ExtractName(char* file1);
printf("%s",s);


}




[解决办法]
strchr(temp, ': '); // string after first ': '
memccpy(pwd,temp, '@ ',at-lpos);
temp这时候还是一个野指针呢
[解决办法]

C/C++ code
#include<iostream>#include<algorithm>#include<string>#include<vector>using namespace std;int main(){    string str = "kevin:pass@127.0.0.1:/var/path/kevin/demo.cpp";    char token[4][3] = {":","@",":/"};    vector<string> sub_str;    int stpos = 0;    int endpos = 0;    int index = 0;    while(index<3)    {    endpos = str.find_first_of(token[index++],stpos);    sub_str.push_back(str.substr(stpos,endpos-stpos));    stpos = endpos+1;    }      //最后的"/"比较特殊,做特殊处理     endpos = str.find_last_of("/",string::npos);    sub_str.push_back(str.substr(stpos+1,endpos-stpos));        sub_str.push_back(str.substr(endpos+1,str.length()));    for(vector<string>::iterator it = sub_str.begin();it!=sub_str.end();++it)    cout<<*it<<endl;        getchar();    return 0;} 

读书人网 >C++

热点推荐