有没有办法将字符串写入文件?

Is there a way I can write a string into a FILE?

本文关键字:文件 字符串 有没有      更新时间:2023-10-16

我正在尝试将字符串写入文件,但我不知道该怎么做,我尝试在我的randomString((字符串函数中使用wstring而不是string,以及其他只是为了将字符串写入文件。

if条件是检查文件是否已创建,如果是,则写入文件。

fopen用于打开文件,path1变量是我的文件的路径,"w"等于写入。

randomString(( 是一个字符串函数。

char buffer[100] = { randomString() };
FILE* file;
file = fopen(path1, "w");
if (file) {
fwrite(buffer, sizeof(char), sizeof(buffer), file);
fclose(file);
}
return;

如果您使用的是新手编译器,则可以尝试std::filesystem

#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
auto directoryToWriteTo = fs::current_path(); // returns a fs::path object
std::ofstream fileStream(directoryToWriteTo.string() + "/nameOfYourFile.txt");
if(fileStream.is_open())
fileStream << "Whatever string you want to write to a filen";
}

写入一个文件不需要std::filesystem,但它确实使迭代目录中所有文件之类的事情变得容易,正如 cppreference.com 示例所改编的那样。

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
auto directoryToTraverse = fs::current_path();
for(auto& p: fs::directory_iterator(directoryToTraverse)){
if(fs::is_regular_file(p)){
std::ofstream tmpStream(p,std::ios_base::app); //open file in append mode
tmpStream << "Append a string to each regular file in your directoryn";
}
}
}

它还允许使用标准 c++ 以编程方式更改文件权限。

如果您只是尝试使用fwrite将字符串的内容打印到文件中,那么您需要执行以下操作

std::string str = randomString();
if ( file ) {
fwrite( str.c_str(), sizeof( char ), str.size(), file );
fclose( file );
}

由于fwrite期望第一个参数是void *的,std::string是不兼容的;然而,char *是兼容的。通过在字符串上调用.c_str(),您将有一个可以使用char *。第二个参数是类型的大小,对于std::stringchar,所以sizeof( char )给出大小(即 1(。第三个参数是计数(要写入的字符数(,可以很容易地从str.size()中获取。