【C语言】【unix c】文件写数据与文件读数据(系统调用函数)

xiaoxiao2021-02-28  59

写数据 write(2): #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); 功能:向文件写数据 参数: fd:指定了具体的文件 buf:指定了内容存放的地址,将这里的内容写到文件 count:指定了文件写入的字节数 返回值:-1 错误 errno被设置 成功 实际写入的字节数 #include <stdio.h> #include <p_file.h> //这里包含了一些头文件 #include <string.h> int main(int argc, char *argv[]) { char *msg = "this is a test!\n"; int fd =open(argv[1], O_WRONLY); if(fd == -1) { perror("open"); return -1; } write(fd, msg, strlen(msg)); close(fd); return 0; } 读数据: read(2): #include <unistd.h> ssize_t read(int fd, void *buf, size_t count); 功能:从文件中读取数据 参数: fd:指定了具体的文件,从这个文件里读取数据, buf:将读取的数据存放在buf指定的地址空间里 count:向系统申请的要读取的字节数 返回值:实际读取到的字节数,0 到达了文件的末尾 -1 错误 errno被设置 #include <stdio.h> #include <p_file.h> #include <string.h> int main(int argc, char *argv[]) { char buf[128]; int fd =open(argv[1], O_RDONLY); if(fd == -1) { perror("open"); return -1; } int r = read(fd, buf, 128);//将内容读入 write(1, buf, r);//将读到的内容从屏幕输出 close(fd); return 0; }
转载请注明原文地址: https://www.6miu.com/read-59269.html

最新回复(0)