-2

我已经构建了一个 .cpp 程序,以便将一些内容写入在 .cpp 文件中创建的 .txt 文件。

我设法编写了所需的内容,但是,当我尝试从终端打开创建的文件时,它说尽管它在那里却找不到它。

当我尝试使用它vinano它的内容打开它时,它是空的。这就像创建一个新文件。

但是,当我在终端外打开它时,我可以看到我想要的内容。

可能是什么问题,我该如何解决这种情况?

贝娄,我已经添加了代码。

问题出在system(buffer)命令上。我收到以下错误:sh: cannot open video2.txt: No such file。我试图从命令提示符打开文件,我得到了上述情况。

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;
}
4

2 回答 2

1

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;

int main(int argc,char* argv[])
{
    fstream RawStipFile;
    RawStipFile.open(strcat(argv[1],".txt"));

Here you modify argv[1]. You append 4 characters to it, without allocating any memory.

string line;
...
char* b;
b = &line[1];
VideoList<<b<<endl;
OutVideoStip.open(strcat(b, ".txt"));

a string takes 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, use string member functions, not strcat.

于 2011-10-12T11:40:51.277 回答
0

只是一个松散的猜测:当前工作目录不一样?

尝试chdir先使用或通过绝对路径打开/home/simon/VideoList.txt

于 2011-10-12T11:43:48.957 回答