C++ Linux读取文件

读取文件时注意:带读取的文件的编码方式,程序编译的编码,都可能影响读取出的内容,单字节打印可查看读取内容;

void getfilecontent(string &result)
{

 char deviceDir[MAXLENTH];//文件路径
 memset(deviceDir, 0, MAXLENTH);

 char current_dir[100];
 memset(current_dir, 0, 100);
 getcwd(current_dir, 100);
  strcat(deviceDir, current_dir);
  strcat(deviceDir,  "/device.xml");

 cout << "deviceDir=" << deviceDir << endl;

 if((access(deviceDir, F_OK)) == -1)//判断文件是否存在
 {
  cout << "device.xml no exist" << endl;
 }
 else{
  try{
  cout << "device.xml Exist" << endl;
  FILE *fp;
  fp = fopen(deviceDir, "r");//打开文件,第二个参数为打开文件方式
  if(fp == NULL)
  {
   cout << "device.xml Open Fail" << endl;
   return;
  }
  fseek(fp, 0, SEEK_END);//设置文件指针到文件结束位置
  int fileLen = ftell(fp);//获得文件的内容长度
  char* pbuf = (char*)malloc(sizeof(char) * fileLen);//申请内存空间
  if (!pbuf)
  {
   cout <<"memory allocation failed!" << endl;
   fclose(fp);
   return;
  }

  fseek(fp, 0, SEEK_SET);//文件指针移动到开头位置
  fread(pbuf, fileLen, 1, fp);//读文件内容1次读取所有,或者每次读取1字节读取fileLen次
  fclose(fp);
  if(fp!=NULL)
  {
   fp = NULL;
  }

/*
  char a =  '\0xAA';
  pbuf[0] =a;
  pbuf[1] = a;
  pbuf[2] = a;

*/
  pbuf[fileLen] = 0;
  result = pbuf;
  for(int i = 0; i < 10; i++)
  {
   cout << i<< pbuf[i] <<endl;
  }
  free(pbuf);

  //cout << "fileSize = "<< fileLen << "result=" << result << endl;
  }
  catch(exception ex)
  {
   cout <<"exception:" <<ex.what()<<endl;
  }
 }

}

猜你喜欢

转载自blog.csdn.net/langhaijing/article/details/82785225