1.结构体写入文件,读取
#include <stdio.h> #include <string.h> #include <stdlib.h> #define max 5 struct books{ char title[20]; char author[20]; 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=0; int addList; if((fp=fopen(fileName,"a+b")) == NULL) { printf("file open fail"); } puts("大侠,你想添加几条数据?"); scanf("%d",&addList); if(addList>0) { do{ printf("please add new book title "); scanf("%s",&bks[i].title); printf("please add new book author "); scanf("%s",&bks[i].author); printf("please add new book price "); scanf("%d",&bks[i].price); i++; fwrite(&bks[i],size,1,fp); }while(i<addList); } } void read(struct books bks[]) { FILE * fp; int i=0; if((fp=fopen(fileName,"r+")) == NULL) { printf("file open fail"); } rewind(fp); while( i<max && fread(&bks[i],size,1,fp) == 1) { printf("title is %s,author is %s,price is %d ",bks[i].title,bks[i].author,bks[i].price); i++; } }
2. 获取指定字符在字符串的最后的位置
1 #include <string.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 int main(int argc,char *argv[]) 6 { 7 if(argc<2) 8 { 9 puts("params error"); 10 exit(1); 11 } 12 13 char *p; 14 char c = argv[2][0]; //传入来的都是字符串,得到需要的字符 ,去掉最后的 15 int weizhi; 16 17 p = strrchr(argv[1],c);//得到字符c在字符串argv[1]中的地址,返回的是字符指针 18 19 if(p) 20 weizhi = p - argv[1]; //两个指针相减,得到位置距离 21 printf("%d",weizhi); 22 else 23 puts("not found"); 24 25 return 0; 26 }
3.字符串查找
1 #include <string.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #define TRUE 1 5 #define FALSE 0 6 #define ERROR 0 7 8 int strStart(char *,char *); 9 10 int main(int argc,char *argv[]) 11 { 12 char message[]="hello,welcome to China"; 13 char find[]="Ch"; 14 int start = strStart(message,find); 15 printf("%d",start); 16 } 17 18 int strStart(char * String,char * find) 19 { 20 int start=-1,i=0,j=0; 21 22 //得到字符串长度 23 int StringLen = strlen(String); 24 int findLen = strlen(find); 25 //判断是否为空 26 if(StringLen<=0 || findLen<=0) 27 { 28 return FALSE; 29 } 30 //判断子串的长度是否大于母串的长度 31 if(StringLen < findLen) 32 { 33 return FALSE; 34 } 35 //开始查找 36 for(i=0;i<=StringLen;i++) 37 { 38 if(String[i]==find[j]) 39 { 40 if(start<0) 41 start = i; 42 43 j++; 44 }else{ 45 if(j<findLen) 46 start=-1; 47 } 48 } 49 return start; 50 }