用C语言的read(),write()编写一个程序来实现复制一个文件的内容到另一个文件,且忽略开头带有“#”的内容
时间: 2024-05-12 18:17:53 浏览: 13
注释”的行。
代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
int fd1, fd2;
char buffer[1024];
int nbytes;
int i = 0;
int pos = 0;
int skip = 0;
if (argc != 3) {
printf("usage: %s source_file dest_file\n", argv[0]);
exit(1);
}
fd1 = open(argv[1], O_RDONLY);
if (fd1 == -1) {
perror("open");
exit(1);
}
fd2 = open(argv[2], O_CREAT | O_TRUNC | O_WRONLY, 0644);
if (fd2 == -1) {
perror("open");
exit(1);
}
while ((nbytes = read(fd1, buffer, sizeof(buffer))) > 0) {
for (i = 0; i < nbytes; i++) {
if (pos == 0 && buffer[i] == '#') {
skip = 1;
}
if (buffer[i] == '\n') {
pos = 0;
skip = 0;
} else {
pos++;
}
if (!skip) {
write(fd2, &buffer[i], 1);
}
}
}
close(fd1);
close(fd2);
return 0;
}
```
解释:
该程序先读取源文件,逐字节匹配是否含有注释符号“#”或换行符“\n”,然后判断是否需要跳过该行,如果不跳过,则将读取到的内容写入目标文件中。最终关闭文件并返回。