I have trouble moving a little of my code from the main one to a function

advertisements

When I run the program as is, it works fine. However when I move the section right after the while loop until cout<<"pp1>" I get two errors. invalid conversion from ‘char’ to ‘const char*’ and initializing argument 2 of ‘char* strncpy(char*, const char*, size_t)’. Any ideas of what I need to change so I can move that code to a function. I cannot find a good explanation online or in my c++ books that explains a way around this. I know that error is saying that it need a literal instead of a pointer, but cannot figure out the work around(is there one?).

Here is my main.

int main(){
       char  cmd_str[500];
       int length=0;
       bool cont=true;
     while(cont){

 // strncpy(cmd_str, infile(), 500 - 1); this line causes the two errors
 // cmd_str[500 - 1] = '\0';

 mode_t perms=S_IRUSR;
 int i=0;
 int fd = open("text.txt",O_RDONLY , perms);
 char *returnArray;
  cout<<fd<<endl;

 if(fd<0){
    perror( strerror(errno));
   } else{
   ifstream readFile;
   readFile.open("text.txt");
   readFile.seekg (0, ios::end);
   int length = readFile.tellg();
   readFile.seekg (0, ios::beg);
   returnArray=new char[i];//memory leak need to solve later
   readFile.getline(returnArray,length);
       cout<<returnArray<<endl;
   strncpy(cmd_str, returnArray, length - 1);
   cmd_str[length - 1] = '\0';

    }

 cout<<"pp1>";
cout<< "test1"<<endl;
//  cin.getline(cmd_str,500);
cout<<cmd_str<<endl;
cout<<"test2"<<endl;
length=0;
    length= shell(returnArray);
cout<<length<<endl;
if(length>=1)
  {
    cout<<"2"<<endl;
  }
else{
  cont=false;
}
  }

}

Here is the function that I have tried

char infile()
{
  mode_t perms=S_IRUSR;
 int i=0;
  int fd = open("text.txt",O_RDONLY , perms);
  char *returnArray;
 cout<<fd<<endl;
if(fd<0){
        perror( strerror(errno));
 }else{
 ifstream readFile;
readFile.open("text.txt");
//int length = readFile.tellg();
readFile.seekg (0, ios::end);
int length = readFile.tellg();
readFile.seekg (0, ios::beg);
returnArray=new char[i];//memory leak need to solve later
readFile.read(returnArray,length);
readFile.getline(returnArray,length);
  }
 return  *returnArray;
}


De-referencing returnArray and trying to return a char is not going to work, since:

  1. You will only return the first character of the string.
  2. The strncpy function will not accept it (which is why you are getting these errors).
  3. You need a way to deallocate the heap allocated memory that the char* takes up.

Change your function definition from char infile() to const char* infile() and return just the pointer alone. This will ideally return the filled array as a const char* (C-style string) which you can pass to strncpy successfully. Futhermore when you're finished with it you need to call delete [] on it (to prevent a memory leak).