【问题标题】:Linux File Read and Write - C++Linux 文件读写 - C++
【发布时间】:2015-05-24 13:53:50
【问题描述】:

我应该创建一个程序来读取 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 char[],因此您应该使用const char * 引用它们以防止意外修改。允许char * 引用字符串文字只是为了向后兼容C,应该强烈避免。二、你怎么知道argv至少包含3个元素?回答:你没有。为这些字符串声明你自己的指针或存储。
  • 这段代码中有很多错误。 read(fid1,buff,count); 其中 count 是 100,但 buff 只有 20 个字符宽。如果您认为这是一个问题,您需要查看您调用的库函数是如何工作的。
  • 分配给argv 是未定义的行为,因为操作系统拥有变量并且可能不会为您提供完整的数组。
  • 谢谢,我将缓冲区更改为 125 字节,它工作了。

标签: c++ linux filesystems system-calls


【解决方案1】:

您应该将文件名分配替换为以下内容:

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

无法保证操作系统会为您的程序分配 3 个变量。

【讨论】:

  • 谢谢。 const stringconst char 更好吗?为什么?
【解决方案2】:

定义一个数组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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多