文件读写文件
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
/*
*STDIN_FILENO 0 标准输入
*STDOUT_FILENO 1 标准输出
*STDERR_FILENO 2 标准错误输出
*/
int main(void)
{
intfdLog = -1;
if((fdLog = open("./log.txt", O_RDWR|O_CREAT|O_TRUNC|O_SYNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0)
{
printf("OpenFile failed:%s", "./log.txt");
return0;
}
/*creat以只写方式创建打开文件
* 等价于open(filename,O_WRONLY|O_CREAT|O_TRUNC, mode);
*/
if(lseek(fdLog, 0, SEEK_CUR) == -1)
{
printf("cannot seek\n");
close(fdLog);
fdLog = -1;
return 0;
}
else
{
printf("seek OK\n");
}
charszBuf[] = "helloworld";
intnWrite = write(fdLog, szBuf, strlen(szBuf));
if(nWrite < 0)
{
printf("writefile failed\n");
close(fdLog);
fdLog= -1;
return0;
}
printf("writedata:%s\n", szBuf);
if(lseek(fdLog, 0, SEEK_SET) == -1)
{
printf("ResetReader Failed\n");
close(fdLog);
fdLog= -1;
}
else
{
printf("reset reader OK\n");
}
charszBuf2[100] = {0};
intnRead = read(fdLog, szBuf2, 100);
if (nRead < 0)
{
printf("readfile Error\n");
close(fdLog);
fdLog= -1;
return0;
}
if(0 == nRead)
{
printf("readNo Data\n");
}
else
{
printf("readData:%s\n", szBuf2);
}
close(fdLog);
fdLog= -1;
return0;
}
执行结果: