Linux 文件读写 - C++
Linux File Read and Write - C++
我应该创建一个程序来读取 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 系统调用。
您应该将文件名分配替换为如下内容:
const std::string source_filename = "source.txt";
const std::string dest1_filename = "destination1.txt";
const std::string dest2_filename = "destination2.txt";
无法保证 OS 会为您的程序分配 3 个变量。
定义一个数组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;
我应该创建一个程序来读取 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 系统调用。
您应该将文件名分配替换为如下内容:
const std::string source_filename = "source.txt";
const std::string dest1_filename = "destination1.txt";
const std::string dest2_filename = "destination2.txt";
无法保证 OS 会为您的程序分配 3 个变量。
定义一个数组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;