简体   繁体   English

Linux文件读写-C ++

[英]Linux File Read and Write - C++

I supposed to create a program that reads source.txt's first 100 characters, write them in destination1.txt, and replace all "2" to "S" and write them to destination2.txt. 我应该创建一个程序,该程序读取source.txt的前100个字符,将它们写入destination1.txt,然后将所有的“ 2”替换为“ S”,然后将它们写入destination2.txt。 Below is my code 下面是我的代码

#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;
}

Thanks guys I am able to do the copying. 谢谢大家,我能够复制。 But how to perform the character replacement? 但是如何执行字符替换? If it's fstream I know how to do it with a for loop. 如果是fstream我知道如何使用for循环来实现。 But I'm supposed to use Linux system calls. 但是我应该使用Linux系统调用。

You should replace the filename assignments to something like this: 您应该将文件名分配替换为以下内容:

const std::string source_filename = "source.txt";
const std::string dest1_filename  = "destination1.txt";
const std::string dest2_filename  = "destination2.txt";

There is no guarantee that the OS will allocate 3 variables to your program. 无法保证操作系统会为您的程序分配3个变量。

Define an array out_buf and copy buff into out_buf character by character, replacing 2's to S. 定义一个数组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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM