Witam!
Napisałem sobie kawałek kodu który działać ma jak cd z wiersza poleceń, ale mam pewien problem z tablicami a dokładniej z ostatnim znakiem kończącym tekst '\0'. Czaem po wpisaniu np. cd c:\folder\folder1 i potem cd .. otrzymuje taką ścieżkę c:\foder Nie wiem gdzie jest błąd.
cd c:\folder
inst_struct_words.word[0] to jest wyraz cd
inst_struct_words.word[1] a to jest ścieżka np. c:\folder
struct inst_cd
{
char* cd;
} inst_struct_cd;
void inst_back_cd()
{
int plast = 0;
int cdLength = strlen(inst_struct_cd.cd);
int i;
for(i = 0; i < cdLength; i++)
{
if(inst_struct_cd.cd[i] == '\\') plast = i;
}
if(plast == 0)
{
return;
}
char* bufo;
bufo = (char*)malloc(plast);
strncpy(bufo, inst_struct_cd.cd, plast+1);
bufo[plast] = 0;
free(inst_struct_cd.cd);
inst_struct_cd.cd = (char*)malloc(plast+1);
strcpy(inst_struct_cd.cd, bufo);
free(bufo);
}
void inst_cd(SOCKET aSocket)
{
if(inst_struct_cd.cd == NULL)
{
inst_struct_cd.cd = (char*)malloc(5);
strcpy(inst_struct_cd.cd, "c:\\");
}
// Dodanie ścieżki z uwzględnieniem:
if((inst_struct_words.word[1].word[0] != '\\') // Jeżeli nazwa pliku nie rozpoczyna sie od znaku wejścia do katalogu ( \ )
&& (inst_struct_words.word[1].word[1] != ':') // Jeżeli nie jest to zmiana dysku
&& (inst_struct_cd.cd[strlen(inst_struct_cd.cd) - 1] != '\\') // Jeżeli ostatni znak zapamiętanej ścieżki ( cd ) nie kończy sie znakiem wejścia do katalogu ( \ )
&& (inst_struct_words.word[1].word[0] != '.') // Jeżeli nie jest to powrót do wcześniejszego katalogu
&& (inst_struct_words.word[1].word[1] != '.')) // Jeżeli nie jest to powrót do wcześniejszego katalogu
{
char* buf;
buf = (char*)malloc(strlen(inst_struct_cd.cd));
strcpy(buf, inst_struct_cd.cd);
free(inst_struct_cd.cd);
inst_struct_cd.cd = (char*)malloc(strlen(strlen(buf) + 1 + inst_struct_words.word[1].word));
strcpy(inst_struct_cd.cd, buf);
strcat(inst_struct_cd.cd, "\\");
strcat(inst_struct_cd.cd, inst_struct_words.word[1].word);
free(buf);
}
// Zmiana dysku, np c:, d: drugi znak to : więc wpisany zostaje nowy dysk
else if(inst_struct_words.word[1].word[1] == ':')
{
free(inst_struct_cd.cd);
inst_struct_cd.cd = (char*)malloc(strlen(inst_struct_words.word[1].word));
strcpy(inst_struct_cd.cd, inst_struct_words.word[1].word);
}
//// Powrót do wcześniejszego katalogu
else if((inst_struct_words.word[1].word[0] == '.') && (inst_struct_words.word[1].word[1] == '.'))
{
// printf("back\n");
inst_back_cd();
}
// Dodanie ścieżki
else
{
char* buf;
buf = (char*)malloc(strlen(inst_struct_cd.cd));
strcpy(buf, inst_struct_cd.cd);
free(inst_struct_cd.cd);
inst_struct_cd.cd = (char*)malloc(strlen(inst_struct_cd.cd) + strlen(inst_struct_words.word[1].word));
strcpy(inst_struct_cd.cd, buf);
strcat(inst_struct_cd.cd, inst_struct_words.word[1].word);
free(buf);
}
printf("%s\n", inst_struct_cd.cd);