I have built a .cpp program in order to write some content to a .txt file created within the .cpp file.
I manage to write the desired content, however, when I am trying to open the created file from terminal, it says that it cannot find it although it is there.
When I try to open it with vi or nano it’s content it’s empty. It is like creating a new file.
However, when I open it outside terminal, I can see its content as I wanted.
What could be the problem and how can I fix this situation?
Bellow, I have added the code.
The problem is with the system(buffer) command. I receive the following error: sh: cannot open video2.txt: No such file. I have tried to opened the files from command prompt and I get the above described situation.
int main(int argc,char* argv[])
{
fstream RawStipFile;
RawStipFile.open(strcat(argv[1],".txt"));
string line;
if (RawStipFile.is_open())
{
getline(RawStipFile, line);
int i = 0;
ofstream OutVideoStip;
ofstream VideoList;
VideoList.open("VideoList.txt");
while ( RawStipFile.good() )
{
getline (RawStipFile,line);
char* l;
l = (char*) malloc(sizeof(char));
l[0]=line[0];
//cout<<line[0]<<endl;
if (line[0]==35)
{
if (OutVideoStip.is_open())
{
OutVideoStip.close();
}
i++;
//char* base;
//base = (char*) malloc(1000*sizeof(char));
//sprintf(base, "%d", i);
char* b;
b = &line[1];
VideoList<<b<<endl;
OutVideoStip.open(strcat(b, ".txt"));
}
else
{
OutVideoStip << line << endl;
}
}
OutVideoStip.close();
RawStipFile.close();
VideoList.close();
}
else
{
cout << "Unable to open file \n";
}
fstream VideoNames;
VideoNames.open("VideoList.txt", fstream::in);
if (VideoNames.is_open())
{
while ( VideoNames.good() )
{
getline(VideoNames, line);
line=line.substr(1,line.length());
if (line.compare(""))
{
string initial = "./txt2mat<";
initial.append(line);
initial.append(".txt>");
initial.append(line);
initial.append(".dat");
cout<<initial<<endl;
const char* buffer;
buffer = initial.c_str();
system(buffer);
}
}
}
else
{
cout<<"Unable to open file. \n";
}
VideoNames.close();
return 0;
}
You are using strcat in a wrong way. I don’t know if that’s the cause of your problem, but it can result in undefined behavour;
Here you modify
argv[1]. You append 4 characters to it, without allocating any memory.a
stringtakes care of it’s own memory management. You can’t asume it has reserved 4 more bytes for you to append. If you need to append, usestringmember functions, not strcat.