1、讀取文件函數(shù)原型介紹
ssize_t read(int fd,void*buf,size_t count)
參數(shù)說明:
fd: 是文件描述符
buf:為讀出數(shù)據(jù)的緩沖區(qū);
count: ? 為每次讀取的字節(jié)數(shù)(是請求讀取的字節(jié)數(shù),讀上來的數(shù)據(jù)保存在緩沖區(qū)buf中,同時文件的當前讀寫位置向后移)
返回值:
?成功:返回讀出的字節(jié)數(shù)
?失?。悍祷?1,并設置errno,如果在調(diào)用read,之前到達文件末尾,則這次read返回0
2、讀取文件函數(shù)示例??
打開終端,輸入以下指令:
?vi demo2.c
?接著輸入如下代碼:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "asdfgh!";
fd = open("./file1",O_RDWR);
if(fd == -1){
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("create file1 success!\n");
}
}
printf("open susceess : fd = %d\n",fd);
// ssize_t write(int fd, const void *buf, size_t count);
int n_write = write(fd,buf,strlen(buf));
if(n_write != -1){
printf("write %d byte to file\n",n_write);
}
char *readBuf;
readBuf = (char *)malloc(sizeof(char)*n_write + 1);
// ssize_t read(int fd, void *buf, size_t count);
int n_read = read(fd, readBuf, n_write);
printf("read %d ,context:%s\n",n_read,readBuf);
close(fd);
return 0;
}
保存退出后,輸入如下指令:
gcc demo2.c?
./a.out
?3、光標移動操作
從運行結果可以看到,并未讀取到內(nèi)容,因為讀取時候光標不在最左側(cè),因此需要進行光標設置。
?光標函數(shù)原型:
off_t lseek(int fd, off_t offset, int whence);
函數(shù)參數(shù)
fd:文件描述符
offset:偏移量
whence:位置
- SEEK_SET:The offset is set to offset bytes. offset為0時表示文件開始位置。
- SEEK_CUR:The offset is set to its current location plus offset bytes. offset為0時表示當前位置。
- SEEK_END:The offset is set to the size of the file plus offset bytes. offset為0時表示結尾位置
函數(shù)返回值
- 成功返回當前位置到開始的長度
- 失敗返回-1并設置errno
?首先輸入如下指令:
vi demo2.c
?輸入以下代碼:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "asdfghi!";
fd = open("./file1",O_RDWR);
if(fd == -1){
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("create file1 success!\n");
}
}
printf("open susceess : fd = %d\n",fd);
int n_write = write(fd,buf,strlen(buf));
if(n_write != -1){
printf("write %d byte to file\n",n_write);
}
char *readBuf;
readBuf = (char *)malloc(sizeof(char)*n_write + 1);
lseek(fd, 0, SEEK_SET);
int n_read = read(fd, readBuf,100);
printf("read %d ,context:%s\n",n_read,readBuf);
close(fd);
return 0;
}
?保存,輸入以下指令:
gcc demo2.c
./a.out
?運行結果如下:
文章來源:http://www.zghlxwxcb.cn/news/detail-672900.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-672900.html
到了這里,關于ubuntu學習(五)----讀取文件以及光標的移動的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!