【发布时间】: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