Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

strtok - Why File is not deleting in C Language

Hello I am new in c and ? have homework about tcp program and one poin in this project I cant pass can anywone help me please

StartsWithDEL() this function catch DEL user.txt like return true trim() like trim and give only file name user.txt

BUT when I write client line DEL user.txt is not going delete

      if (StartsWithDEL(line,"DEL") == 1)
            {
                 char *deltoken = strtok(line, "DEL");
                 char *itemDeleting = trim(deltoken);
//in this section I cach file name but cant delete it 
                    remove(itemDeleting);
                    send(client, "
" ,strlen("
"),0);
    
             }

enter image description here

question from:https://stackoverflow.com/questions/65648026/why-file-is-not-deleting-in-c-language

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your call to strtok() in incorrect. The second argument is a string or allowed token delimiters, which in your case a . If you call it with "DEL", it will overwrite the D with and deltoken will point to that empty string.

If you choose to use strtok() then:

char* token = strtok( line, " " ) ;

if( strcmp( token, "DEL" ) == 0 )
{
    char* itemDeleting = strtok( NULL, " " ) ;
    remove(itemDeleting);
    send(client, "
" ,strlen("
"),0);
}

However if is simpler to avoid the complexity of strtok(), and the fact that it modifies line by inserting nuls makes it undesirable in many cases. The code above also won't work if a filename may contains spaces.

There are many alternative solutions, for example:

size_t delimiter_index = strcspn( line, " " ) ;

if( strncmp( line, "DEL", delimiter_index ) == 0 )
{
    char* itemDeleting = &line[delimiter_index] ;
    while( *itemDeleting == 0 && *itemDeleting != '' ) itemDeleting++ ;

    remove(itemDeleting);
    send(client, "
" ,strlen("
"),0);
}

Since I have no idea what StartsWithDEL() or trim() so I have avoided them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...