【问题标题】:Replace name of a file with the first line of its contents将文件名替换为其内容的第一行
【发布时间】:2013-03-15 23:54:58
【问题描述】:

我有多个扩展名为 *.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");
}

感谢您的帮助 干杯

【问题讨论】:

    标签: c++ file filenames rename


    【解决方案1】:

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

    你想要这样的东西:

    result= rename(oldname , test[0].c_str());
    

    (并删除newname)。

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

    【讨论】:

      【解决方案2】:

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

      #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());
      }
      

      【讨论】:

      • 好的,非常感谢。两个答案都正常工作。但是接下来..如何将静态文件名(“./test.txt”)更改为扩展名为txt的文件夹中的所有文件?
      • @VictorVector 这将从标准输入中获取文件名列表,并根据第一行重命名每个文件名:pastebin.com/RG7w3AUH 您可以在 Windows 中像这样使用它(如果应用程序名为 ' app.exe': dir /b *.txt | app.exe ,linux和mac都可以使用ls *.txt | app.exe
      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2013-09-09
      • 2020-10-31
      相关资源
      最近更新 更多