有没有办法将字符串写入文件?
Is there a way I can write a string into a FILE?
我正在尝试将字符串写入文件,但我不知道该怎么做,我尝试在我的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::string
是char
,所以sizeof( char )
给出大小(即 1(。第三个参数是计数(要写入的字符数(,可以很容易地从str.size()
中获取。
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- C 通过char读取文件字符串的文件char;崩溃
- 我不明白如何将 toupper 和 isalpha 与.txt文件字符串输入一起使用
- 在 CPP 文件中使用 make 文件字符串变量
- 编译 PyGAMMA Mac Lion:g++ 找不到标准的 C++ 头文件(字符串/iostream..)
- 如何在c++中使用文件字符串作为命令
- 使用 TinyXML 解析 XML 文件字符串
- 递归下降解析器帮助(不读取文本文件字符串)