在linux中有两中想文件中写内容的函数
第一种方法用c的方法读文件
#include <sys/types.h>#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char* argv[])
{
int value;
int write_value;
value=open("/root/myprogram/test/mylog.info",O_CREAT|O_RDWR|O_APPEND);
if (value == -1)
{
printf("open file fail\n");
return 0;
}
else
{
int count=0;
do{
printf("open file success\n");
time_t now;
struct tm *timenow;
time(&now);
timenow=localtime(&now);
printf("now time is:%s\n",asctime(timenow));
char *current_time=asctime(timenow);
printf("current_time is :%s\n",current_time);
printf("current_time size is :%d\n",strlen(current_time));
int test=10;
char str[255];
sprintf(str," %d",test);
strcat(str," \t ");
strcat(str,current_time);
printf("my str is :%s\n",str);
write_value= write(value,str,strlen(str));
}while(count++ < 10);
close(value);
#if 0
if(write_value==-1)
{
printf("write file fail\n");
return 0;
}else{
int v=10;
char buf[255];
//itoa(v,buf,10);
sprintf(buf,"%d",v);
//strcpy(buf," '\0' ");
printf("buf is :%s \n",buf);
printf("write file success\n");
write(value,buf,strlen(buf));
close(value);
}
#endif
return 0;
}
}
第二种方法,以C++的形式实现,这种很简单
#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace std;
void myfunction(const int);
int main(int argc,char *argv[])
{
//ofstream in("/root/myprogram/test/log.info",ios::app);
// char *str="Hello";
//in<<"Hello";
//in.close();
int a=100;
myfunction(a);
return 0;
}
void myfunction(const int a)
{
ofstream out("/root/myprogram/test/log.info",ios::app);
char str[255];
sprintf(str,"%d",a);
strcat(str,"\t");
out<<str;
out.close();
}
ifstream 把文件作为输入,就是将文件的内容输出到变量中,ofstream把文件作为输出,就是向文件里面写内容