【问题标题】:Add two variables to make a path of directory添加两个变量以创建目录路径
【发布时间】:2023-04-09 01:14:01
【问题描述】:

我想连接"/sdcard/hello.txt" 的目录路径,但我的问题是前半部分(/sdcard)在#define format 中定义,第二部分是const char *file_path("/hello.txt"),这是我从用户那里获取的。

因此,要创建完整路径,我必须将这两部分连接起来以创建目录的完整路径。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define MOUNT_POINT "/sd_card"
using namespace std;

class SD_Card {
 public:
  void sd_card_init(void);
  void create_and_writeFile(const char* file_path);
};


void SD_Card::create_and_writeFile(const char* file_path) {

  // First create a file.
  //const char *file_hello = MOUNT_POINT"/hello.txt";

  const char* file_hello = strcat(MOUNT_POINT, file_path);

  ESP_LOGI(TAG, "Opening file %s", file_hello);
  FILE* f = fopen(file_hello, "w");
  if (f == NULL) {
    ESP_LOGE(TAG, "Failed to open file for writing");
    return;
  }

  fprintf(f, "Hello %s!\n", card->cid.name);
  fclose(f);
  ESP_LOGI(TAG, "File written");
}

void app_main() {
  SD_Card cObj;
  cObj.create_and_writeFile("/hello.txt");
}


我收到此错误:

/main/SD_Card.cpp: In member function 'void SD_Card::create_and_writeFile(const char*)':
  ../main/SD_Card.cpp:144:63: warning: ISO C++ forbids converting a string constant to 'char*' 
  [-Wwrite-strings]
      const char *file_hello = strcat(MOUNT_POINT,file_path);

我是 CPP 的新手,请帮助我了解如何操作。

提前致谢。

【问题讨论】:

  • 如果您有 C++ 编译器,请使用 C++ STL fstreamstring
  • strcat 将修改第一个参数并将第二个参数的内容放入第一个参数的内存中。但是您将不可修改的字符串文字作为第一个参数传递,因此编译器(正确地)抱怨。用std::string代替C函数确实会简单很多。
  • 感谢您的回复,能否请您分享一些示例代码,我已尝试但无法正常工作。
  • 几年以来,我们在 C++ 中有一个 filesystem 库。请参阅此处:en.cppreference.com/w/cpp/filesystem 您需要的一切都已经存在。如果你阅读 cppreference,你会发现很多例子。

标签: c++ string pointers char constants


【解决方案1】:

strcat 将使用第一个参数作为目标。您所做的事情是错误的,因为您将字符串文字 ("/sdcard") 指定为目标。

由于您使用的是 ESP API,我假设您希望继续使用 C'ish 编程并避免使用 STL 和朋友,因此可以解决问题的最少代码涉及 printing into a buffer

#define BUFFER_SIZE 100

{
  // Remove this line:
  // const char *file_hello = strcat(MOUNT_POINT,file_path);

  char buf[BUFFER_SIZE];
  snprintf(buf, BUFFER_SIZE, "%s%s", MOUNT_POINT, file_path);
  // buf now holds the concatenated strings :) 

  ESP_LOGI(TAG, "Opening file %s", buf);
  FILE* f = fopen(buf, "w");
}

当然如果你可以使用标准库,问题毕竟被标记为C++,你可以简单地这样做:

#include <string>

const string MOUNT_POINT{"/sdcard"};

{
  auto file_hello = MOUNT_POINT + file_path;

  // The rest is similar, use `.c_str()` to pass a C string e.g.
  FILE *f = fopen(file_hello.c_str(), "w");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2021-09-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多