gpt4 book ai didi

c++ - Linux 文件读写 - C++

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:30 25 4
gpt4 key购买 nike

我应该创建一个程序来读取source.txt的前100个字符,将它们写入destination1.txt,并将所有“2”替换为“S”并将它们写入destination2.txt。下面是我的代码

#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdio>
#include <iostream>

using namespace std;

int main(int argc, const char* argv[]){
argv[0] = "source.txt";
argv[1] = "destination1.txt";
argv[2] = "destination2.txt";
int count=100;
char buff[125];
int fid1 = open(argv[0],O_RDWR);

read(fid1,buff,count);
close(fid1);

int fid2 = open(argv[1],O_RDWR);
write(fid2,buff,count);
close(fid2);

//How to change the characters?
return 0;
}

谢谢大家,我可以复制了。但是如何进行角色替换呢?如果它是fstream,我知道如何用for循环来做到这一点。但我应该使用 Linux 系统调用。

最佳答案

定义一个数组out_buf,并将buff逐个字符复制到out_buf中,将2替换为S。

...
read(fid1,buff,count);
close(fid1);

char out_buf [125];
int i;
for (i = 0; i < sizeof (buf); i++) {
if (buff [i] == '2')
out_buf [i] = 'S'
else
out_buf [i] = buff [i]
}
int fid2 = open(argv[1],O_RDWR);
write(fid2, out_buf,count);
close(fid2);

return 0;

关于c++ - Linux 文件读写 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29178671/

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