简体   繁体   中英

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. 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. But I'm supposed to use Linux system calls.

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.

Define an array out_buf and copy buff into out_buf character by character, replacing 2's to 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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