gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:20:18 25 4
gpt4 key购买 nike

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

例如:文件.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");
}

感谢帮助干杯

最佳答案

不是直接回答你的代码,因为它看起来已经被处理过,但如果你只需要第一行(没有错误检查),这应该做你想做的事

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

关于c++ - 用文件内容的第一行替换文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15632802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com