c++ - std::rename() 文件在使用 char 变量作为参数时不起作用(字符串转换为 char)

标签 c++ string char

我试过在字符串 tablename4tablename5 的开头和结尾添加 "\"",然后再将其转换为 char ,并且 rename() 函数仍然不起作用。它确实可以通过将实际文件名作为 rename() 参数放入,但这不是我想要的,我想使用 char 变量

完整编译代码:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>  
#include <iomanip>
#include <stdio.h>
using namespace std;
using std::string;

int main()
{

    std::string tablename4 = "hello.txt";
    ifstream in4(tablename4);
    ofstream out8("temp2.txt");

    std::string convertthis2;
    convertthis2 = "\"" + tablename4 + "\"";
    char * tochar2 = new char[convertthis2.length()];
    strcpy_s(tochar2, (convertthis2.length() + 1), convertthis2.c_str());

    std::string convertthis3;
    std::string tablename5 = "temp2.txt";
    convertthis3 = "\"" + tablename5 + "\"";
    char * tochar3 = new char[convertthis3.length()];
    strcpy_s(tochar3, (convertthis3.length() + 1), convertthis3.c_str());
    in4.close();
    out8.close();
    rename(tochar3, tochar2);

    //below is testing to see if it converted right, but these print out fine, as "hello.txt" and "temp2.txt"
    //but i tried it with and without the quotation marks, rename() still doesnt work
    cout << tochar2 << "     " << tochar3;

    return 0;
}

最佳答案

稍微简化并纠正 2 个错误:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
using std::string;

int main()
{

    std::string tablename4 = "hello.txt";
    ifstream in4(tablename4);
    ofstream out8("temp2.txt");

    std::string convertthis2 = string("\"") + tablename4 + "\"";

    std::string tablename5 = "temp2.txt";
    std::string convertthis3 = string("\"") + tablename5 + "\"";
    in4.close();
    out8.close();
    rename(convertthis3.c_str(), convertthis2.c_str());

    //below is testing to see if it converted right, but these print out fine, as "hello.txt" and "temp2.txt"
    //but i tried it with and without the quotation marks, rename() still doesnt work
    cout << convertthis2 << "     " << convertthis3 << endl;

    return 0;
}

问题是您正在分配一个等于 string 对象长度的字节数组,然后将这些数组用作 c 风格的字符串。然而,c 风格的字符串必须有一个终止零,您不添加它 - 因此是未定义的行为。

注意上面.c_str() 成员变量的使用。它完全符合您的要求 - 以安全的方式使 std::string 看起来像 C 风格的字符串。

如果您发现自己正在编写 C 代码,那是因为您将从阅读 STL 文档中受益。

关于c++ - std::rename() 文件在使用 char 变量作为参数时不起作用(字符串转换为 char),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32938512/

相关文章:

javascript - 本练习中 substr 方法和 slice 方法有什么区别?

java - 方法正在更改我的类变量 char[][] 但我不知道为什么 java

C++ "::"没有类名

java - 如何创建一个显示字符串数组的方法

c++ - move std::thread 时出现链接错误?

java - 将字符串转换为 JSON 对象数组并解析它们

c - 读取一个字符串并将其转换为 2D int 矩阵 C

C++ Char - 关系运算符

c++ - cpp中的构造函数无限循环

c++ - 分配器作为 vector 和列表中的默认参数