1.结构体写入文件,读取
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define max 5struct books{
char title[];
char author[];
int price;
};const char * fileName="books.txt";
int size=sizeof(struct books);void read(struct books bks[]);
void write(struct books bks[]);
void list(struct books bks[]);
void demo(struct books bks[]);void main(void)
{
struct books bks[max]; //write(bks);
read(bks);}void write(struct books bks[])
{
FILE * fp;
int i=;
int addList;
if((fp=fopen(fileName,"a+b")) == NULL)
{
printf("file open fail");
} puts("大侠,你想添加几条数据?");
scanf("%d",&addList); if(addList>)
{
do{
printf("please add new book title\n");
scanf("%s",&bks[i].title);
printf("please add new book author\n");
scanf("%s",&bks[i].author);
printf("please add new book price\n");
scanf("%d",&bks[i].price);
i++;
fwrite(&bks[i],size,,fp);
}while(i<addList);
}}void read(struct books bks[])
{
FILE * fp;
int i=;
if((fp=fopen(fileName,"r+")) == NULL)
{
printf("file open fail");
} rewind(fp); while( i<max && fread(&bks[i],size,,fp) == )
{
printf("title is %s,author is %s,price is %d\n",bks[i].title,bks[i].author,bks[i].price);
i++;
}}
2. 获取指定字符在字符串的最后的位置
#include <string.h>
#include <stdio.h>
#include <stdlib.h> int main(int argc,char *argv[])
{
if(argc<)
{
puts("params error");
exit();
} char *p;
char c = argv[][]; //传入来的都是字符串,得到需要的字符 ,去掉最后的\0
int weizhi; p = strrchr(argv[],c);//得到字符c在字符串argv[1]中的地址,返回的是字符指针 if(p)
weizhi = p - argv[]; //两个指针相减,得到位置距离
printf("%d",weizhi);
else
puts("not found"); return ;
}
3.字符串查找
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define ERROR 0 int strStart(char *,char *); int main(int argc,char *argv[])
{
char message[]="hello,welcome to China";
char find[]="Ch";
int start = strStart(message,find);
printf("%d",start);
} int strStart(char * String,char * find)
{
int start=-,i=,j=; //得到字符串长度
int StringLen = strlen(String);
int findLen = strlen(find);
//判断是否为空
if(StringLen<= || findLen<=)
{
return FALSE;
}
//判断子串的长度是否大于母串的长度
if(StringLen < findLen)
{
return FALSE;
}
//开始查找
for(i=;i<=StringLen;i++)
{
if(String[i]==find[j])
{
if(start<)
start = i; j++;
}else{
if(j<findLen)
start=-;
}
}
return start;
}