1.read函数
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
返回值:成功返回读取的字节数,出错返回-1并设置errno,如果在调read之前已到达文件末尾,则这次read返回0。
参数count:请求读取的字节数,读上来的数据保存在缓冲区buf中,同时文件的当前读写位置向后移。
实例:从终端读取字符串。
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif
int main(int argc, char const *argv[])
{
int bytes;
char str[1024] = "";
//从终端读取数据
if ((bytes = read(0, str, 6)) == -1)
{
perror("fail to read file:");
return -1;
}
printf("str=%s", str);
printf("bytes=%d", bytes);
return 0;
}
终端输入字符串长度大于6则返回6,终端输入的字符串长度小于6则返回实际读取长度+1,因为最后会接收回车字符。
实例:从文件读取字符串
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif
#define N 1024
int main(int argc, char const *argv[])
{
int fd;
fd = open("test.txt", O_CREAT | O_RDONLY, 0664);
if (fd == -1)
{
perror("fail to open file:");
return -1;
}
char buff[N];
int bytes = 0;
if ((bytes = read(fd, buff, N)) == -1)
{
perror("fail to read file:");
return -1;
}
printf("buff=%s", buff);
printf("bytes=%d", bytes);
return 0;
}
假设程序当前路径下存在test.txt文件,且文件内容如下:
hello,linux!
我爱你中国
注意:为了避免出现中文乱码,建议test.txt使用gbk字符集保存。
测试运行:
buff=hello,linux!
我爱你中国
bytes=24
如果我们不知道要读取的文件长度是多少字节,推荐使用以下循环方式读取,直到读取到文件结尾。
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif
#define N 1024
int main(int argc, char const *argv[])
{
int fd;
fd = open("test.txt", O_CREAT | O_RDONLY, 0664);
if (fd == -1)
{
perror("fail to open file:");
return -1;
}
char buff[N];
int bytes = 0;
while ((bytes = read(fd, buff, N)) != 0)
{
printf("buff=%s", buff);
}
return 0;
}