// TestCFile.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
char* substr(const char*str,unsigned start, unsigned end);
char * getFirst(char str[]);
char* getValue(char str[]);
void writeAfter(char buffer[]);
void del(char id[]);
char* searchByID(char id[]);
char *path = "/home/magc/software/test1.txt";
char *dest = "D:/123.txt";
char buffer[255];
/*截取字符串*/
char* substr(const char*str,unsigned start, unsigned end)
{
unsigned n = end - start;
static char stbuf[256];
strncpy(stbuf, str + start, n);
stbuf[n] = 0;
return stbuf;
}
char * getFirst(char str[])
{
int firstComma=strstr(str,",")-str;
if(firstComma!=-1)//当str中存在,号的时候
{
return substr(str,0,firstComma);
}else
{
return "nothing was found";
}
}
/*得到命令中的值 如 add,xxx,x,xx,xx结果是 xxx,x,xx,xx*/
char* getValue(char str[])
{
int firstComma=strstr(str,",")-str;
if(firstComma!=-1)//当str中存在,号的时候
{
return substr(str,firstComma+1,strlen(str)-1);
}else
{
return "values not found";
}
}
void writeAfter(char buffer[])
{
printf("writeAfter");
FILE *df = fopen(dest,"at");
if(df!=NULL)
{
printf("df is not null");
//gets(buffer);//--------buffer来自于控制台的输入
strcat(buffer,"\n");
fputs(buffer,df);
}
//fclose(df);
}
/*根据ID来删除*/
/*实际上就是逐行遍历 将不是以此ID开头的都保存起来然后覆盖原文件*/
void del(char id[])
{
char firstWord[255];
FILE *df = fopen(dest,"r");
//存放所有读取的信息的二维字符串数组
char lines[255][255];
int lineNo=0;
char line[255];//一行信息
while(fgets(line,255,df)!=NULL)
{
printf(line);//原本的文件信息中已经带有了换行符号 这里的line也是带有换行符号的//故这里不使用puts
strcpy(firstWord,getFirst(line));//得到第一个值 例如 本来是001,xxx,xxx,xxx 应该得到001
if(strcmp(firstWord,id)!=0) //如果该行的id不是我们要找的id 那么 我们应该记住此行
{
strcpy(lines[lineNo++],line);
}else
{
//什么也不做
}
}
//重新写入文件 覆盖写
FILE *wf=fopen(dest,"w");
for(int i=0;i<lineNo;i++)
{
fputs(lines[i],wf);
}
fclose(df);
fclose(wf);
}
/*根据ID来查找*/
/*输入 001 找到的结果是 001,xxx,xx,\n 找到的每条信息本身末尾带有\n*/
char* searchByID(char id[])
{
char firstWord[255];
FILE *df = fopen(dest,"r");
char line[255];//一行信息
while(fgets(line,255,df)!=NULL)
{
//printf(line);//原本的文件信息中已经带有了换行符号 这里的line也是带有换行符号的//故这里不使用puts
strcpy(firstWord,getFirst(line));//得到第一个值 例如 本来是001,xxx,xxx,xxx 应该得到001
if(strcmp(firstWord,id)==0) //如果该行的id是我们要找的id 找到了!
{
break;
}else
{
//什么也不做
}
}
fclose(df);
return line;
}
//int _tmain(int argc, _TCHAR* argv[])
//{
// //成功运行!
// //char id[]="003";
// //del(id);
//
// /*测试del*/
// //char str[]="add,xxxx,xxx,xxx";
// //printf(substr(str,0,3));//正确输出add
// //strcpy(str,"search,xxxx");
// //printf(getFirst(str));//正确输出search
// //strcpy(str,getFirst("001,xxx,xxx,xx"));
// //printf(str);//正确得到001
//
//
// /*测试查找*/
// char str[255];
// strcpy(str,searchByID("001"));
// printf(str);
//
// char c[255];
// gets(c);
//}