c写入内存 写入文件
原载于:文章来源:www.forasp.cn网站制作学习
c读取内存写入到文件
在同事的帮助下,写了个c程序代码,实现的功能是:输入内容,并放入到内存缓存中,到达一定大小后,写入到文件中。代码如下,并加上了解释:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
/*上面是引入的标准库*/
int maxsize =32;/*定义区域大小为32字节*/
void * getlocp(){/*获取一块内存区域,并返回区域指针*/
void *t;
t = malloc(maxsize);
if(t==NULL){
printf("error");
exit(0);
}
return t;
}
/*定义写入文件函数,并采用移动到后面追加内容*/
void writeloc(void *buffer){
int fd;
int n;
fd = open("forasp.txt", O_CREAT|O_WRONLY);
lseek(fd,0,2);
if(fd<0){
perror("open error");
exit(0);
}
n=write(fd, buffer, maxsize);
if(n<0){
printf("write error");
exit(0);
}
close(fd);
printf("has been writed \n");
}
/*这里是主函数*/
int main(int argc, char *argv[])
{
void *temp,*p;
char *getint;
int writenum,i;
writenum = 0;i=0;
p = getlocp();
temp = p;
for(;;){
scanf("%s",getint);/*等待输入内容,然后将内容写入到申请的内存中*/
if(writenum+sizeof(getint)<maxsize){
writenum=writenum+sizeof(getint);
memcpy(temp,getint,sizeof(getint));
temp+=sizeof(getint);
}else{
writeloc(p);
temp=p;
writenum=0;
i++;
}
printf("%d,%d",i,writenum);
if(i==3)exit(0);
}
return 0;
}
代码不多,我错了不少,经验:
1.看调用的系统函数,需要什么样的头文件要引入
2.调用函数,如果要定义在前面,或者前面定义,后面重载实现
3.熟悉对应系统函数的参数
4.懂得基本的debug操作。
<%77w%77%2Ef%6F%72p%73%70%2Ec%6E>