[英]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";
無法保證操作系統會為您的程序分配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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.