[国嵌攻略][074][系统调用方式文件编程]
2016-02-27 10:54
429 查看
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> void main(){ //打开文件 int fd; fd = open("./test.c", O_RDWR | O_CREAT, 0777); if(fd < 0 ){ printf("File not exist!\n"); } //写入文件 char wbuf[10] = "12345"; write(fd, wbuf, 5); //定位文件 lseek(fd, 0, SEEK_SET); //读取文件 char rbuf[10]; read(fd, rbuf, 5); rbuf[5] = '\0'; //打印内容 printf("Read buffer is %s\n", rbuf); close(fd); }
复制文件程序
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char **argv){ //参数检查 if(argc != 3){ printf("Usage:\n\t./copy <source file> <distance file>\n"); return -1; } //打开文件 int srcFd, dstFd; srcFd = open(argv[1], O_RDONLY); dstFd = open(argv[2], O_WRONLY | O_CREAT, 0777); //复制文件 int count; char buffer[512]; count = read(srcFd, buffer, 512); while(count > 0){ write(dstFd, buffer, count); count = read(srcFd, buffer, 512); } //关闭文件 close(srcFd); close(dstFd); return 0; }
相关文章推荐
- C++基础总结(1)--基本数据类型范围
- C++基础总结(1)--基本数据类型范围
- 多线程socket编程--聊天程序
- 【leetcode】【9】Palindrome Number
- [2016/02/27] PAT(Basic Level) Problem 1001-1050 JAVA略解
- Java类文件结构(Class文件)
- 1、梯度下降c代码
- 当项目使用SpringMvc时拦截器的注意事项
- Python实现简单多线程任务队列
- Java应用场景的解决框架资源大全
- java一个类获取另一个类的变量值
- 第一行代码-9.5 服务的更多技巧
- Thinking in Java---多线程仿真:银行出纳员仿真+饭店仿真+汽车装配工厂仿真
- 搞笑代码注释
- Spring Security 3.x完整入门配置教程及其代码下载
- Delphi函数详解:全局函数,内部函数,类的成员函数,类的静态方法
- C++: 解释error: call of overloaded ‘abs(int)’ is ambiguous
- 【leetcode】【8】String to Integer (atoi)
- 第一行代码-9.4 服务的生命周期
- 【leetcode】【7】Reverse Integer