linux文件操作

在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把文件作为输出,就是向文件里面写内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值