感觉像是写施工日志
int main()
{
int fd;
fd = open("./file2",O_RDWR); //描述见上;
if(fd == -1)
{
printf("file2文件不存在\n");
}
fd = open("./file2",O_RDWR|O_CREAT,0764);
printf("fd=%d \n",fd);
char* buf= "wohenshuai";
write(fd,buf,strlen(buf));
int n_write = write(fd,buf,strlen(buf));
printf("write %d byte to file \n",n_write);
close(fd); //描述见下文;
fd = open("./file2",O_RDWR);
char* readBuf;
readBuf = (char*)malloc(sizeof(char)*n_write+1);
int n_read = read(fd,readBuf,n_write);
printf("read %d ; context:%s \n",n_read,readBuf);
close(fd);
return 0;
}
//光标目前定位在最后一个字节,关闭文件后重新打开,定位到文件首字节,等待读取命令;
新方法
lseek(fd,0,SEEK_SET);//代替关闭文件重新打开这种方式的定位光标;0为偏移值;
SEEK_SET; 头
SEEK_GND; 尾
int main()
{
int fd;
fd = open("./file2",O_RDWR);
if(fd == -1)
{
printf("file2文件不存在\n");
}
fd = open("./file2",O_RDWR|O_CREAT,0764);
printf("fd=%d \n",fd);
char* buf= "wohenshuai";
int n_write = write(fd,buf,strlen(buf));
printf("write %d byte to file \n",n_write);
lseek(fd,0,SEEK_SET);
char* readBuf;
readBuf = (char*)malloc(sizeof(char)*n_write+1);
int n_read = read(fd,readBuf,n_write);
printf("read %d ; context:%s \n",n_read,readBuf);
int fileSize = lseek(fd,0,SEEK_END);
printf("file's size is:%d \n",fileSize);
close(fd);
return 0;
}
遇到的问题:使用read函数读取文件后面乱码
表示分配的内存空间不足,用sizeof()*XX,多倍字节;
文件内容查找和代替
未学习前的自用代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()//int argc,char **argv
{
int fdScr;
fdScr = open("./file2",O_RDWR);
char *strData;
lseek(fdScr,0,SEEK_SET);
char* readBuf;
readBuf = (char*)malloc(sizeof(char)*128);
int n_read = read(fdScr,readBuf,128);
printf("read %d ; context:%s \n",n_read,readBuf);
char *strOld = "LENG";
char * p = strstr(readBuf,strOld);
printf("%p,%s",p,p);
char * strOldNum = "3";
char * pNum = strstr(p,strOldNum);
printf("%p,%s \n",pNum,pNum);
int setnum;
setnum = n_read - strlen(pNum);
lseek(fdScr,setnum,SEEK_SET);
char* newBuf= "5";
int n_write = write(fdScr,newBuf,strlen(newBuf));
pNum = "5";
printf("new: %p,%s \n",pNum,pNum);
lseek(fdScr,0,SEEK_SET);
n_read = read(fdScr,readBuf,128);
printf("read %d ; context:%s \n",n_read,readBuf);
return 0;
}
C语言标准库中的读写
读写字符函数putc:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
int i;
char * str = "wohenshuai";
int len = strlen(str);
fp = fopen("./file4","w+");
for(i=0;i<len;i++)
{
fputc(*str,fp);
str++;
}
fclose(fp);
return 0;
}
读写字符串函数puts:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
int i;
char * str = "wohenshuai";
int len = strlen(str);
fp = fopen("./file4","w+");
fputs(str,fp);
fclose(fp);
return 0;
}