C++ 用文件内容的第一行替换文件名

C++ 用文件内容的第一行替换文件名,c++,file,filenames,rename,C++,File,Filenames,Rename,我有多个扩展名为*.txt的文件,在这些文件中,我想读取它们的第一行并重命名为文件名 例如:file.txt 在这个文件中,第一行是:X_1_1.1.X_1_X 并将其重命名为:X_1_1.1.X_1_X.txt 我从其他项目中重写了这段代码,但它将我的文件重命名为随机字母,并且不知道如何更正它 #include<iostream> #include<fstream> using namespace std; int main() { int size=28000

我有多个扩展名为*.txt的文件,在这些文件中,我想读取它们的第一行并重命名为文件名

例如:file.txt

在这个文件中,第一行是:X_1_1.1.X_1_X

并将其重命名为:X_1_1.1.X_1_X.txt

我从其他项目中重写了这段代码,但它将我的文件重命名为随机字母,并且不知道如何更正它

#include<iostream>
#include<fstream>
using namespace std;
int main()

{
   int size=28000;
   string *test = new string[rozmiar];
   std::fstream file;
   std::string line;
   file.open("C:\\file.txt",std::ios::in);  
   int line_number=0;
   while((file.eof() != 1))
   {
    getline(file, line);
    test[line_number]=line;
    line_number++;
   }

   file.close();
   cout << "Enter line number in the file to be read: \n";
   cin >> line_number;
   cout << "\nYour line number is:";
   cout << test[0] << " \n";
   char newname[25];
   test[0]=newname;
   int result;
   char oldname[] ="C:\\file.txt";
   result= rename(oldname , newname);

   if (result == 0)
      puts ("File successfully renamed");
   else
      perror("Error renaming file");
}
#包括
#包括
使用名称空间std;
int main()
{
int size=28000;
字符串*测试=新字符串[rozmiar];
std::fstream文件;
std::字符串行;
file.open(“C:\\file.txt”,std::ios::in);
int line_number=0;
而((file.eof()!=1))
{
getline(文件,行);
测试[线路编号]=线路;
行数++;
}
file.close();
cout>行数;

不能以任何方式初始化
newname
。这就是问题所在

你想要这样的东西:

result= rename(oldname , test[0].c_str());
(并删除
newname


在您的代码中,
newname
是完全未初始化的,因此您会在文件名中看到随机字符。

不是对代码的直接回答,因为它看起来已经被处理过了,但是如果您只需要第一行(无错误检查),这应该可以满足您的需要

#包括
#包括
int main()
{
静态std::字符串常量文件名(“./test.txt”);
std::字符串行;
{
std::ifstream文件(filename.c_str());//如果使用c++11,则不需要c_str()
getline(文件,行);
}
重命名(filename.c_str(),(line+“.txt”).c_str());
}

好的,非常感谢。两个答案都正确。但是下一件事..如何将静态文件名(“./test.txt”)更改为文件夹中所有扩展名为txt的文件?@VictorVector这将从标准输入中获取文件名列表,并根据第一行重命名每个文件:您可以在windows中像这样使用它(如果应用程序名为'app.exe':
dir/b*.txt | app.exe
,linux和mac可以使用
ls*.txt | app.exe
#include <fstream>
#include <string>

int main()
{
    static std::string const filename("./test.txt");

    std::string line;
    {
        std::ifstream file(filename.c_str()); // c_str() not needed if using C++11
        getline(file, line);
    }

    rename(filename.c_str(), (line + ".txt").c_str());
}