C切割割字符串并转换为整形
1、strstr函数使用
2、atoi函数使用
3、标准文件IO操作
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#if 0
int main()
{
char a[]="123,33,44,55";
char *needle=",";
char *haystack=a; //不能直接char *haystack="aaa||a||bbb||c||ee||"; 会报内存不能写错误
char* buf = strstr( haystack, needle);
while( buf != NULL ) {
buf[0]='\0'; //在出现分隔符的位置设置结束符\0
printf( "str is %s\n", haystack);
int temp=atoi(haystack);
printf("num = %d\n",temp);
haystack = buf + strlen(needle);
buf = strstr( haystack, needle);
}
}
#else
int main()
{
FILE *fp = NULL;
int i = 0;
char array[256] = {0};
char *buf;
//char Major[3] = {0}; //主版本
//char Minor[3] = {0}; //次版本
//char Revision[3] = {0};//修订版本
//char _Revision[4] = {0}; //保留
unsigned char version[4] = {0};
if(access("/mnt/hgfs/工控机学习/test",F_OK) < 0)
return -1;
if((fp = fopen("/mnt/hgfs/工控机学习/test/boot.v","r")) == NULL)
{
printf("fopen is failed \n");
return -1;
}
fseek(fp,7,SEEK_SET);
fread(array,sizeof(array),1,fp);
printf("array is %s\n",array);
char *data = array;
buf = strstr(data,".");
version[0] = (unsigned char)atoi(data);
printf("num = %d\n",version[0]);
data = buf + 1;
buf = strstr(data,".");
version[1] = (unsigned char)atoi(data);
printf("num = %d\n",version[1]);
data = buf + 1;
version[2] = (unsigned char)atoi(data);
printf("num = %d\n",version[2]);
fclose(fp);
}
#endif
运行结果