C++代码:
#include <string>
#include <fstream>
#include <iostream>
bool fileDelete(std::string path,std::string str1)
{
//ect/profile文件去掉ulimit配置
std::ifstream in(path.c_str());
if(!in.is_open())
{
return false;
}
std::string strFileData = "";
std::string lineStr = "";
while(std::getline(in,lineStr))
{
//std::cout << lineStr<<std::endl;
if (lineStr != str1)
{
strFileData += lineStr;
strFileData += "\n";
}
}
in.close();
//写入文件
if(!strFileData.empty())
{
std::cout << strFileData<<std::endl;
std::ofstream out(path.c_str());
out.is_open();
out.flush();
out<<strFileData;
out.close();
}
else
{
return false;
}
return true;
}
bool fileAppend(std::string path,std::string str1)
{
bool flag = false;
std::ifstream in(path.c_str());
if(!in.is_open())
{
return false;
}
std::string strFileData = "";
std::string lineStr = "";
while(std::getline(in,lineStr))
{
//std::cout << lineStr<<std::endl;
if(lineStr == str1)
flag = true;
strFileData += lineStr;
strFileData += "\n";
}
if(!flag)
{
strFileData += str1;
strFileData += "\n";
}
in.close();
//写入文件
if(!strFileData.empty())
{
std::cout << strFileData<<std::endl;
std::ofstream out(path.c_str());
out.is_open();
out.flush();
out<<strFileData;
out.close();
}
else
{
return false;
}
return true;
}
c语言代码:
int fileDelete(char* FileName,char str[256])
{
int Lid=0;
int MaxLine=0;
FILE* fp=NULL;
char Buf[256]="";
char tmp[100][256]={0};
if ((fp = fopen(FileName, "r+")) == NULL)
{
printf("Can't open file!/n");
return 0;
}
while (fgets(Buf, 256, fp))
{
Lid++;
if (strcmp(Buf,str) != 0)
{
strcpy(tmp[Lid], Buf);
}
}
MaxLine = Lid;
rewind(fp);
fclose(fp);
//remove(FileName); // 删除原文件
if((fp = fopen(FileName, "w")) == NULL)
{
printf("@@@@@@@@Can't open etc/profile!/n");
return 0;
}
for(Lid = 1; Lid <= MaxLine; Lid++)
{
fputs(tmp[Lid], fp);
}
fclose(fp);
return 1;
}
int fileAppend(char* FileName, char str[256])
{
int flag = -1;
int Lid=0;
int MaxLine=0;
FILE* fp=NULL;
char Buf[256]="";
char tmp[50][256]={0};
if ((fp=fopen(FileName,"r+")) == NULL)
{
printf("@@@@@@@@@Can't open etc/profile!/n");
return 0;
}
while (fgets(Buf, 256 ,fp))
{
Lid++;
if(strcmp(Buf,str) == 0)
{
flag = 0;
}
strcpy(tmp[Lid],Buf);
}
if(-1 == flag)
strcpy(tmp[Lid++],str);
MaxLine=Lid;
rewind(fp);
for(Lid=1 ;Lid <= MaxLine;Lid++)
{
fputs(tmp[Lid],fp);
}
fclose(fp);
return 1;
}