- 论坛徽章:
- 0
|
如何用c将一个文件从一个目录拷到另一个目录去?
偶也来凑个热闹,各位大哥可不要笑话小弟的程序写的丑喔.
- #include <stdio.h>;
- #include <sys/stat.h>;
- #include <fcntl.h>;
- #include <string.h>;
- int main(int argc, char* argv[])
- {
- int srcfd, destfd;
- char content[128];
- char* ptr;
- if (argc != 2) {
- fprintf(stderr, "Usage: %s [source file]\n", argv[0]);
- exit(1);
- }
- srcfd = open(argv[1], O_RDONLY);
- if (srcfd < 0) {
- perror("open");
- exit(1);
- }
- if (read(srcfd, content, 128) < 0) {
- perror("read");
- exit(2);
- }
- content[strlen(content) - 1] = '\0'; /* get rid of the '\n' */
- ptr = strchr(content, '='); /* get the position of the '=' */
- *ptr = '\0'; /* separate the string into 2 strings */
- destfd = open(++ptr, O_WRONLY | O_CREAT | O_TRUNC, 0644);
- if (destfd < 0) {
- perror("creat");
- exit(3);
- }
- if (write(destfd, content, strlen(content)) < 0) {
- perror("write");
- exit(4);
- }
- close(srcfd);
- close(destfd);
- exit(0);
- }
复制代码
PS.本程序在RH8.0, GCC3.3下测试通过 |
|