|
发表于 2023-8-21 17:46:59
|
显示全部楼层
以下是一个使用C语言编写的程序,可以在Linux环境中实现您的需求:
- #include <stdio.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <unistd.h>
- int main() {
- // 打开或创建源文件 src.txt
- int src_fd = open("src.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
- if (src_fd == -1) {
- perror("open src.txt failed");
- return 1;
- }
- // 获取源文件的大小
- off_t file_size = lseek(src_fd, 0, SEEK_END);
- lseek(src_fd, 0, SEEK_SET);
- // 读取源文件内容
- char buffer[file_size];
- ssize_t bytes_read = read(src_fd, buffer, sizeof(buffer));
- if (bytes_read == -1) {
- perror("read src.txt failed");
- close(src_fd);
- return 1;
- }
- // 创建目标文件 dst.txt
- int dst_fd = open("dst.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
- if (dst_fd == -1) {
- perror("create dst.txt failed");
- close(src_fd);
- return 1;
- }
- // 写入目标文件
- ssize_t bytes_written = write(dst_fd, buffer, bytes_read);
- if (bytes_written == -1) {
- perror("write dst.txt failed");
- close(src_fd);
- close(dst_fd);
- return 1;
- }
- // 修改目标文件的权限为所有用户可读写
- if (chmod("dst.txt", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) == -1) {
- perror("chmod dst.txt failed");
- close(src_fd);
- close(dst_fd);
- return 1;
- }
- close(src_fd);
- close(dst_fd);
- // 输出目标文件的内容
- FILE* dst_file = fopen("dst.txt", "r");
- if (dst_file == NULL) {
- perror("open dst.txt failed");
- return 1;
- }
- int ch;
- while ((ch = fgetc(dst_file)) != EOF) {
- putchar(ch);
- }
- fclose(dst_file);
- return 0;
- }
复制代码
这个程序使用 open 函数打开或创建源文件 src.txt,然后使用 read 函数读取其内容到缓冲区。接着,使用 open 函数创建目标文件 dst.txt,并使用 write 函数将缓冲区的内容写入到目标文件。然后,使用 chmod 函数修改目标文件的权限为所有用户可读写。最后,使用 fopen 函数打开目标文件,并使用 fgetc 函数遍历文件并输出其内容。
请注意,上述程序中使用了系统调用来完成文件操作,对于错误处理也进行了相应的处理。如果编译并执行此程序,将在当前目录下创建或打开 src.txt 和 dst.txt 文件,并将 src.txt 的内容复制到 dst.txt,并修改 dst.txt 的权限为所有用户可读写。最后,程序将输出 dst.txt 的内容。
希望以上信息能帮助到您!如果您有任何其他问题,请随时提问。
如果问题已经解决,请设置最佳答案 |
|