Мой код для изменения текущего каталога в C ++ продолжает давать мне ошибку Segmentation Fault: 11 - PullRequest
0 голосов
/ 11 января 2020

Вот код:

#include <iostream>
#include "unistd.h"
using namespace std;

int main(){

char *directory = NULL;

cout << "Enter the directory you want to enter: ";

//taking input
cin >> directory;

//changing the directory
chdir(directory);

return 0;
}

Мой компилятор говорит, что ошибка возникает в строке 7 (char *directory = NULL;)

Любая помощь с этим будет оценена.

Ответы [ 2 ]

0 голосов
/ 11 января 2020

использовать <> для файла в библиотеке компилятора

#include <iostream>
#include <unistd.h>  // 
using namespace std;

int main()
{
   string directory;

   cout << "Enter the directory you want to enter: " << endl;

   //taking input
   cin >> directory;

   //changing the directory
   chdir(&directory[0]);

   return 0;
}
0 голосов
/ 11 января 2020

Это не имеет ничего общего с chdir(), скорее проблема в том, что вы говорите cin записать данные через нулевой указатель.

Правильное решение - использовать std::string для хранения строка пути вместо:

#include <string>
#include <iostream>
#include <unistd.h>

int main()
{
   std::string directory;

   std::cout << "Enter the directory you want to enter: " << std::endl;

   //taking input
   std::cin >> directory;

   //changing the directory
   chdir(directory.c_str());

   return 0;
}
...