百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

分享几个实用的嵌入式C程序(嵌入式c语言是干什么的)

toyiye 2024-07-08 23:17 17 浏览 0 评论


在学习和工作开发的时候,经常需要使用到各种各样不太常用的操作,这种情况一般是自己手动写一些小程序来处理。因为它们不太常用,所以经常用了又没保存,等到下一次在使用的时候又需要重写,这样的非常浪费时间和精力。

所以想在这里统一记录一下,以备下次重新使用。代码以实用为主,如果缺陷,欢迎指出。

1、十六进制字符转整型数字

功能:将16进制的字符串转换为10进制的数字。我是没有找到相应的库函数,所以参考网上的代码自己手动写了个函数来实现。

常用的函数有atoi,atol,他们都是将10进制的数字字符串转换为int或是long类型,所以在有些情况下不适用。

/*=============================================================================
#     FileName: hex2dec.cpp
#         Desc: Convert a hex string to a int number
#       Author: Caibiao Lee
#      Version: 
#   LastChange: 2018-11-26 
#      History:
=============================================================================*/
 
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <ctype.h>
 
int c2i(char ch)  
{  
    // 如果是数字,则用数字的ASCII码减去48, 如果ch = '2' ,则 '2' - 48 = 2  
    if(isdigit(ch))  
            return ch - 48;  
 
    // 如果是字母,但不是A~F,a~f则返回  
    if( ch < 'A' || (ch > 'F' && ch < 'a') || ch > 'z' )  
            return -1;  
 
    // 如果是大写字母,则用数字的ASCII码减去55, 如果ch = 'A' ,则 'A' - 55 = 10  
    // 如果是小写字母,则用数字的ASCII码减去87, 如果ch = 'a' ,则 'a' - 87 = 10  
    if(isalpha(ch))  
            return isupper(ch) ? ch - 55 : ch - 87;  
 
    return -1;  
} 
 
int hex2dec(char *hex)  
{  
    int len;  
    int num = 0;  
    int temp;  
    int bits;  
    int i;  
    char str[64] = {0};
 
 if(NULL==hex)
 {
  printf("input para error \n");
  return 0;
 }
 
 
 if(('0'==hex[0])&&(('X'==hex[1])||('x'==hex[1])))
 {
  strcpy(str,&hex[2]);
 }else
 {
  strcpy(str,hex);
 }
 
 printf("input num = %s \n",str);
 
    // 此例中 str = "1de" 长度为3, hex是main函数传递的  
    len = strlen(str);  
 
    for (i=0, temp=0; i<len; i++, temp=0)  
    {  
            // 第一次:i=0, *(str + i) = *(str + 0) = '1', 即temp = 1  
            // 第二次:i=1, *(str + i) = *(str + 1) = 'd', 即temp = 13  
            // 第三次:i=2, *(str + i) = *(str + 2) = 'd', 即temp = 14  
            temp = c2i( *(str + i) );  
            // 总共3位,一个16进制位用 4 bit保存  
            // 第一次:'1'为最高位,所以temp左移 (len - i -1) * 4 = 2 * 4 = 8 位  
            // 第二次:'d'为次高位,所以temp左移 (len - i -1) * 4 = 1 * 4 = 4 位  
            // 第三次:'e'为最低位,所以temp左移 (len - i -1) * 4 = 0 * 4 = 0 位  
            bits = (len - i - 1) * 4;  
            temp = temp << bits;  
 
            // 此处也可以用 num += temp;进行累加  
            num = num | temp;  
    }  
 
    // 返回结果  
    return num;  
}  
 
int main(int argc, char **argv)
{
 int l_s32Ret = 0;
 
 if(2!=argc)
 {
  printf("=====ERROR!======\n");
  printf("usage: %s Num \n", argv[0]);
  printf("eg 1: %s 0x400\n", argv[0]);
  return 0;
 }
 
 l_s32Ret = hex2dec(argv[1]);
 printf("value hex = 0x%x \n",l_s32Ret);
 printf("value dec = %d \n",l_s32Ret);
 return 0;
}

运行结果:

biao@ubuntu:~/test/flash$ ./a.out 0x400
input num = 400 
value hex = 0x400 
value dec = 1024 
biao@ubuntu:~/test/flash$ 

2、字符串转整型

功能:将正常输入的16进制或是10进制的字符串转换为int数据类型。

/*=============================================================================
#     FileName: hex2dec.cpp
#         Desc: Convert a hex/dec string to a int number
#       Author: Caibiao Lee
#      Version: 
#   LastChange: 2018-12-03 
#      History:
=============================================================================*/
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <ctype.h>
 
int String2int(char *strChar)
{
 int len=0;
 const char *pstrCmp1="0123456789ABCDEF";
 const char *pstrCmp2="0123456789abcdef";
 
 char *pstr=NULL;
 int uiValue=0;
 int j=0; 
 unsigned int t=0;
 int i=0;
 if(NULL==strChar)
  return -1;
 if(0>=(len=strlen((const char *)strChar)))
  return -1;
 if(NULL!=(pstr=strstr(strChar,"0x"))||NULL!=(pstr=strstr(strChar,"0X")))
 {
  pstr=(char *)strChar+2;
  
  if(0>=(len=strlen((const char *)pstr)))
   return -1;
  for(i=(len-1);i>=0;i--)
  {
   if(pstr[i]>'F')
   {
    for(t=0;t<strlen((const char *)pstrCmp2);t++)
    { 
     if(pstrCmp2[t]==pstr[i])
      uiValue|=(t<<(j++*4));
    }
   }
   else
   {
    for(t=0;t<strlen((const char *)pstrCmp1);t++)
    { 
     if(pstrCmp1[t]==pstr[i])
      uiValue|=(t<<(j++*4));
    }
   }
  }
 }
 else
 {
  uiValue=atoi((const char*)strChar);
 }
 return uiValue;
}
 
int main(int argc, char **argv)
{
 int l_s32Ret = 0;
  
 if(2!=argc)
 {
  printf("=====ERROR!======\n");
  printf("usage: %s Num \n", argv[0]);
  printf("eg 1: %s 0x400\n", argv[0]);
  return 0;
 }
 l_s32Ret = String2int(argv[1]);
 printf("value hex = 0x%x \n",l_s32Ret);
 printf("value dec = %d \n",l_s32Ret);
 return 0;
}

嵌入式物联网需要学的东西真的非常多,千万不要学错了路线和内容,导致工资要不上去!

无偿分享大家一个资料包,差不多150多G。里面学习内容、面经、项目都比较新也比较全!某鱼上买估计至少要好几十。

点击这里找小助理0元领取:嵌入式物联网学习资料(头条)




3、创建文件并填充固定数据

功能:创建固定大小的一个文件,并且把这个文件填充为固定的数据。

/*=============================================================================
#     FileName: CreateFile.cpp
#         Desc: 创建固定大小的文件,然后填充固定的数据
#       Author: Caibiao Lee
#      Version: 
#   LastChange: 2018-11-26 
#      History:
=============================================================================*/
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <ctype.h>
 
//#define FILL_DATA_VALUE  0xff
#define FILL_DATA_VALUE  0x30 //char 0
 
int c2i(char ch)  
{  
    if(isdigit(ch))  
            return ch - 48;  
 
    if( ch < 'A' || (ch > 'F' && ch < 'a') || ch > 'z' )  
            return -1;  
 
    if(isalpha(ch))  
            return isupper(ch) ? ch - 55 : ch - 87;  
 
    return -1;  
} 
 
int hex2dec(char *hex)  
{  
    int len;  
    int num = 0;  
    int temp;  
    int bits;  
    int i;  
    char str[64] = {0};
 
 if(NULL==hex)
 {
  printf("input para error \n");
  return 0;
 }
 
 if(('0'==hex[0])&&(('X'==hex[1])||('x'==hex[1])))
 {
  strcpy(str,&hex[2]);
 }else
 {
  strcpy(str,hex);
 }
 
 printf("input num = %s \n",str);
 
    len = strlen(str);  
 
    for (i=0, temp=0; i<len; i++, temp=0)  
    {  
            temp = c2i( *(str + i) );  
 
            bits = (len - i - 1) * 4;  
            temp = temp << bits;  
 
            num = num | temp;  
    }  
    return num;  
}  
 
int main(int argc, char **argv)
{
 FILE *l_pFile = NULL;
 int  l_s32Rest = 0;
 unsigned int l_WriteLen = 0;
 unsigned int l_FileLen = 0;
 unsigned char TempData[1024] = {FILL_DATA_VALUE};
 
 if(3!=argc)
 {
  printf("usage: %s FileName  FileLen \n ", argv[0]);
  printf("eg: %s ./Outfile.bin 0x400 \n ", argv[0]);
  return 0;
 };
 
 const char *l_pFileName = argv[1];
 if(NULL==l_pFileName)
 {
  printf("input file name is NULL \n");
  return -1;
 }
 
 if(('0'==argv[2][0])&&(('X'==argv[2][1])||('x'==argv[2][1])))
 {
  l_FileLen = hex2dec(argv[2]);
  
 }else
 {
  l_FileLen = atoi(argv[2]);
 }
 
 printf("Need To Write Data Len %d \n",l_FileLen);
 printf("Fill Data Vale = 0x%x \n",FILL_DATA_VALUE);
 
 for(int i=0;i<1024;i++)
 {
  TempData[i] = FILL_DATA_VALUE;
 }
 
 
 l_pFile = fopen(l_pFileName,"w+");
 if(l_pFile==NULL)
 {
  printf("open file %s error \n",l_pFileName);
  return -1;
 }
 
 
 while(l_WriteLen<l_FileLen)
 {
  if(l_FileLen<1024)
  {
   l_s32Rest = fwrite(TempData,1,l_FileLen,l_pFile);
   
  }
  else
  {
   l_s32Rest = fwrite(TempData,1,1024,l_pFile);
  }
 
  if(l_s32Rest <= 0)
  {
   break;
  };
 
  l_WriteLen +=l_s32Rest; 
 }
 
 if(NULL!=l_pFile)
 {
  fclose(l_pFile);
  l_pFile = NULL;
 }
 
 return 0;
 
}

运行结果:

biao@ubuntu:~/test/flash$ gcc CreateFile.cpp 
biao@ubuntu:~/test/flash$ ls
a.out  CreateFile.cpp  hex2dec.cpp  main.cpp  out.bin
biao@ubuntu:~/test/flash$ ./a.out ./out.bin 0x10
input num = 10 
Need To Write Data Len 16 
Fill Data Vale = 0x30 
biao@ubuntu:~/test/flash$ ls
a.out  CreateFile.cpp  hex2dec.cpp  main.cpp  out.bin
biao@ubuntu:~/test/flash$ vim out.bin 
  1 0000000000000000                                     

4、批量处理图片

功能:批处理将图片前面固定的字节数删除。

/*=============================================================================
#     FileName: CutFile.cpp
#         Desc: 批量处理,将图片的前面固定字节删除
#       Author: Caibiao Lee
#      Version: 
#   LastChange: 2018-11-26 
#      History:
=============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
 
 
#define START_READ_POSITION  128
#define PHOTO_START_TIME  83641
//l_s32PhotoTime = 92809;
 
int Cut_file(char * InputFile)
{
 FILE *l_pFileInput = NULL;
 FILE *l_pFileOutput = NULL;
 char l_ars8OutputName[128] = {0};
 unsigned char l_arru8TempData[1024] = {0};
 int l_s32Ret = 0;
 static unsigned int ls_u32Num = 0;
 
 
 if(NULL== InputFile) 
 {
  goto ERROR;
 }
 
 //sprintf(l_ars8OutputName,"./outfile/_%s",&InputFile[8]);
 sprintf(l_ars8OutputName,"./outfile/00%d.jpg",ls_u32Num++);
 
 //printf("out file name %s \n",l_ars8OutputName);
 
 l_pFileInput = fopen(InputFile,"rb+");
 if(NULL==l_pFileInput)
 {
  printf("input file open error\n");
  goto ERROR;
 }
 
 l_pFileOutput = fopen(l_ars8OutputName,"w+");
 if(NULL==l_pFileOutput)
 {
  printf("out file open error\n");
  goto ERROR;
 }
 
 fseek(l_pFileInput,START_READ_POSITION,SEEK_SET);
 
 while(!feof(l_pFileInput))
 {
  l_s32Ret = fread(l_arru8TempData,1,1024,l_pFileInput);
  if(l_s32Ret<0)
  {
   break;
  }
 
  l_s32Ret = fwrite(l_arru8TempData,1,l_s32Ret,l_pFileOutput);
  if(l_s32Ret<0)
  {
   break;
  }
 }
 
ERROR:
 if(NULL!=l_pFileOutput)
 {
  fclose(l_pFileOutput);
  l_pFileOutput =NULL;
 };
 
 if(NULL !=l_pFileInput);
 {
  fclose(l_pFileInput);
  l_pFileInput =NULL;
 }
}
 
int main(void)
{
 char l_arrs8InputName[128] = {0};
 char l_s8PhotoChannel = 0;
 int  l_s32PhotoTime = 0;
 
 l_s8PhotoChannel = 3;
 l_s32PhotoTime = PHOTO_START_TIME;
 
 /**从第一通道开始**/
 for(int j=1;j<l_s8PhotoChannel;j++)
 {
 
  for(int i=l_s32PhotoTime;i<235959;i++)
  {
   memset(l_arrs8InputName,0,sizeof(l_arrs8InputName));
   sprintf(l_arrs8InputName,"./image/%dY%06d.jpg",j,i);
 
   if(0==access(l_arrs8InputName,F_OK))
   {
    printf("%s\n",l_arrs8InputName);
    Cut_file(l_arrs8InputName);    
   }
  }
 }
}

运行结果:

biao@ubuntu:~/test/photo$ gcc CutFile.cpp 
biao@ubuntu:~/test/photo$ ls
a.out  CutFile.cpp  image  outfile
biao@ubuntu:~/test/photo$ ./a.out 
./image/1Y083642.jpg
./image/1Y083714.jpg
./image/1Y083747.jpg
./image/1Y083820.jpg
./image/1Y083853.jpg
./image/1Y083925.jpg
./image/1Y084157.jpg
./image/1Y084228.jpg
./image/1Y084301.jpg
./image/1Y084334.jpg
./image/1Y084406.jpg
./image/1Y084439.jpg
./image/1Y084711.jpg
./image/1Y084742.jpg
./image/1Y173524.jpg
./image/1Y173556.jpg
./image/1Y173629.jpg
./image/1Y173702.jpg
./image/1Y173933.jpg
./image/1Y174004.jpg
./image/1Y174244.jpg
./image/1Y174315.jpg
./image/1Y174348.jpg
./image/1Y174420.jpg
./image/1Y174454.jpg
./image/1Y174733.jpg
biao@ubuntu:~/test/photo$ tree
.
├── a.out
├── CutFile.cpp
├── image
│   ├── 1Y083642.jpg
│   ├── 1Y083714.jpg
│   ├── 1Y083747.jpg
│   ├── 1Y083820.jpg
│   ├── 1Y083853.jpg
│   ├── 1Y083925.jpg
│   ├── 1Y084157.jpg
│   ├── 1Y084228.jpg
│   ├── 1Y084301.jpg
│   ├── 1Y084334.jpg
│   ├── 1Y084406.jpg
│   ├── 1Y084439.jpg
│   ├── 1Y084711.jpg
│   ├── 1Y084742.jpg
│   ├── 1Y173524.jpg
│   ├── 1Y173556.jpg
│   ├── 1Y173629.jpg
│   ├── 1Y173702.jpg
│   ├── 1Y173933.jpg
│   ├── 1Y174004.jpg
│   ├── 1Y174244.jpg
│   ├── 1Y174315.jpg
│   ├── 1Y174348.jpg
│   ├── 1Y174420.jpg
│   ├── 1Y174454.jpg
│   └── 1Y174733.jpg
└── outfile
    ├── 000.jpg
    ├── 0010.jpg
    ├── 0011.jpg
    ├── 0012.jpg
    ├── 0013.jpg
    ├── 0014.jpg
    ├── 0015.jpg
    ├── 0016.jpg
    ├── 0017.jpg
    ├── 0018.jpg
    ├── 0019.jpg
    ├── 001.jpg
    ├── 0020.jpg
    ├── 0021.jpg
    ├── 0022.jpg
    ├── 0023.jpg
    ├── 0024.jpg
    ├── 0025.jpg
    ├── 002.jpg
    ├── 003.jpg
    ├── 004.jpg
    ├── 005.jpg
    ├── 006.jpg
    ├── 007.jpg
    ├── 008.jpg
    └── 009.jpg
 
2 directories, 54 files
biao@ubuntu:~/test/photo$ 

运行前需要创建两个目录,image用来存放需要处理的图片,outfile用来存放处理过后的文件。这种处理文件批处理方式很暴力,偶尔用用还是可以的。

5、IO控制小程序

嵌入式设备系统一般为了节省空间,一般都会对系统进行裁剪,所以很多有用的命令都会被删除。在嵌入式设备中要调试代码也是比较麻烦的,一般只能看串口打印。现在写了个小程序,专门用来查看和控制海思Hi3520DV300芯片的IO电平状态。

/*=============================================================================
#     FileName: Hi3520_IO_CTRL.cpp
#         Desc: Hi3520DV300 IO Write and  Read
#       Author: Caibiao Lee
#      Version: 
#   LastChange: 2018-11-30
#      History:
=============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include "hstGpioAL.h"
 
int PrintfInputTips(char *ps8Name)
{
 printf("=========== error!!! ========\n\n");
 printf("usage Write: %s GPIO bit value \n", ps8Name);
 printf("usage Read : %s GPIO bit \n", ps8Name);
 printf("eg Write 1 to GPIO1_bit02  :     %s 1 2 1\n", ps8Name);
 printf("eg Read  GPIO1_bit02 Value :     %s 1 2 \n\n", ps8Name);
 
 printf("=============BT20==================\n")
 printf("USB HUB    GPIO_0_2  1_UP; 0_Down \n");
 printf("RESET_HD   GPIO_13_0 0_EN; 1_disEN\n");
 printf("Power_HD   GPIO_13_3 1_UP; 0_Down \n");
 return 0;
}
 
int main(int argc, char **argv)
{
 if((3!=argc)&&(4!=argc))
 {
  PrintfInputTips(argv[0]);
  return -1;
 }
 
 unsigned char l_u8GPIONum = 0;
 unsigned char l_u8GPIOBit = 0;
 unsigned char l_u8SetValue = 0;
 
 GPIO_GROUP_E  l_eGpioGroup;
 GPIO_BIT_E   l_eBit;
 GPIO_DATA_E   l_eData;
 
 l_u8GPIONum   = atoi(argv[1]);
 l_u8GPIOBit   = atoi(argv[2]);
 
 if(l_u8GPIONum<14)
 {
  l_eGpioGroup = (GPIO_GROUP_E)l_u8GPIONum;
 }else
 {
  printf("l_u8GPIONum error l_u8GPIONum = %d\n",l_u8GPIONum);
  return -1;
 };
 
 if(l_u8GPIOBit<8)
 {
  l_eBit = (GPIO_BIT_E)l_u8GPIOBit;
 }else
 {
  printf("l_u8GPIOBit error l_u8GPIOBit = %d\n",l_u8GPIOBit);
  return -1;
 }
 
 if(NULL!=argv[3])
 {
  l_u8SetValue = atoi(argv[3]);
  if(0==l_u8SetValue)
  {
   l_eData = (GPIO_DATA_E)l_u8SetValue;
  }else if(1==l_u8SetValue)
  {
   l_eData = (GPIO_DATA_E)l_u8SetValue;
  }else
  {
   printf("l_u8SetValue error l_u8SetValue = %d\n",l_u8SetValue);
  }
 }
 
 if(3==argc)                                                       
 {/**read**/                                                                                                                                                      
     printf("read GPIO%d Bit%d \n",l_u8GPIONum,l_u8GPIOBit);           
        /**set input**/                                               
        HstGpio_Set_Direction(l_eGpioGroup, l_eBit, GPIO_INPUT);                        
                                                                                          
     /**read **/                                                                               
     char l_s8bit_val = 0;                                                                     
     HstGpio_Get_Value(l_eGpioGroup, l_eBit, &l_s8bit_val);                                    
                                                                                               
     printf("read Data = %d \n",l_s8bit_val);                                                  
                                                                                                 
   }else if(4==argc)                                                                             
   {/**write**/                                                                                                                                                                            
       printf("Write GPIO %d; Bit %d; Value %d\n",l_u8GPIONum,l_u8GPIOBit,l_u8SetValue);         
                                                                                                 
       /***set IO output*/                                                                       
       HstGpio_Set_Direction(l_eGpioGroup, l_eBit, GPIO_OUPUT);                                  
                                                                                                 
       /**Write To IO**/ 
    HstGpio_Set_Value(l_eGpioGroup,l_eBit,l_eData);
   }else                                            
   {                                                                                             
                                                                                                 
   }
 
 return 0;
 
}

6、文件固定位置插入数据

在文件的固定位置插入固定的数据。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define BASIC_FILE_NAME  "./nandflash.bin"
#define UBOOT_FILE_NAME  "./u-boot.bin"
#define KERNEL_FILE_NAME "./kernel.bin"
#define ROOTFS_FILE_NAME "./rootfs.bin"
#define APP_FILE_NAME  "./app.bin"
 
 
#define UBOOT_POSITION  0x00
#define KERNEL_POSITION  0x100000
#define ROOTFS_POSITION  0x500000
#define APP_POSITION  0x2700000
 
 
 
int InsertData(FILE *pfBasic,FILE *psInsert,int s32Position)
{
 int l_S32Ret = 0;
 unsigned char l_arru8Temp[1024] = {0xff};
 
 fseek(pfBasic,s32Position,SEEK_SET);
 fseek(psInsert,0,SEEK_SET);
 while(1)
 {
  l_S32Ret = fread(l_arru8Temp,1,1024,psInsert);
  if(l_S32Ret > 0)
  {
   l_S32Ret = fwrite(l_arru8Temp,1,l_S32Ret,pfBasic);
   if(l_S32Ret<=0)
   {
    printf("line %d error l_S32Ret = %d \n",__LINE__,l_S32Ret);
    return -1;
   }
  }else
  {
   break;
  }
 }
 
 return 0;
}
 
 
 
int main(void)
{
 int l_s32Ret = 0;
 FILE *l_pfBasec = NULL;
 FILE *l_pfUboot = NULL;
 FILE *l_pfKernel = NULL;
 FILE *l_pfRootfs = NULL;
 FILE *l_pfApp = NULL;
 
 
 l_pfBasec = fopen(BASIC_FILE_NAME,"r+");
 if(NULL==l_pfBasec)
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 l_pfUboot = fopen(UBOOT_FILE_NAME,"r");
 if(NULL==l_pfUboot)
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 l_pfKernel = fopen(KERNEL_FILE_NAME,"r");
 if(NULL==l_pfKernel)
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 l_pfRootfs = fopen(ROOTFS_FILE_NAME,"r");
 if(NULL==l_pfRootfs)
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 l_pfApp = fopen(APP_FILE_NAME,"r");
 if(NULL==l_pfApp)
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 if(0> InsertData(l_pfBasec,l_pfUboot,UBOOT_POSITION))
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 if(0> InsertData(l_pfBasec,l_pfKernel,KERNEL_POSITION))
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 if(0> InsertData(l_pfBasec,l_pfRootfs,ROOTFS_POSITION))
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 if(0> InsertData(l_pfBasec,l_pfApp,APP_POSITION))
 {
  printf("line %d error \n",__LINE__);
  goto ERROR;
 }
 
 
ERROR:
 if(NULL!=l_pfBasec)
 {
  fclose(l_pfBasec);
  l_pfBasec = NULL;
 }
 
 if(NULL!=l_pfUboot)
 {
  fclose(l_pfUboot);
  l_pfUboot = NULL;
 }
 
 if(NULL!=l_pfKernel)
 {
  fclose(l_pfKernel);
  l_pfKernel = NULL;
 }
 
 
 if(NULL!=l_pfRootfs)
 {
  fclose(l_pfRootfs);
  l_pfRootfs = NULL;
 }
 
 if(NULL!=l_pfApp)
 {
  fclose(l_pfApp);
  l_pfApp = NULL;
 }
 
 return 0;
}

7、获取本地IP地址

在linux设备中获取本地IP地址可以使用下面的程序,支持最大主机有三个网口的设备,当然这个网卡数可以修改。

#include <stdio.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
 
int get_local_ip(char *ps8IpList)
{
    struct ifaddrs *ifAddrStruct;
    char l_s8IpAddr[INET_ADDRSTRLEN];
    void *tmpAddrPtr;
    int l_s32IPCount = 0;
    
    getifaddrs(&ifAddrStruct);
    while (ifAddrStruct != NULL) 
    {
        if (ifAddrStruct->ifa_addr->sa_family==AF_INET)
        {
            tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
            inet_ntop(AF_INET, tmpAddrPtr, l_s8IpAddr, INET_ADDRSTRLEN);
            if (strcmp(l_s8IpAddr, "127.0.0.1") != 0) 
            {
                if(l_s32IPCount == 0)
                {
                        memcpy(ps8IpList, l_s8IpAddr, INET_ADDRSTRLEN);
                } else 
                {
                        memcpy(ps8IpList+INET_ADDRSTRLEN, l_s8IpAddr, INET_ADDRSTRLEN);
                }
                l_s32IPCount++;
            }
        }
        ifAddrStruct=ifAddrStruct->ifa_next;
    }
 
    freeifaddrs(ifAddrStruct);
    return l_s32IPCount;
}
 
int main()
{
    char l_arrs8IpAddrList[3][INET_ADDRSTRLEN];
    int l_s32AddrCount;
    
    memset(l_arrs8IpAddrList, 0, sizeof(l_arrs8IpAddrList));
 
    l_s32AddrCount = get_local_ip(*l_arrs8IpAddrList);
 
    for(l_s32AddrCount;l_s32AddrCount>0;l_s32AddrCount--)
    {
        printf("Server Local IP%d: %s\n",l_s32AddrCount,l_arrs8IpAddrList[l_s32AddrCount-1]);
    }
 
 return 0;
}

原文链接:https://mp.weixin.qq.com/s/Pd9yNdeg4qvwjQG2sed_-w

文章转载自:嵌入式大杂烩

文章来源于:分享几个实用的嵌入式C程序!

原文链接:分享几个实用的嵌入式C程序!

版权声明:本文来源于网络,免费传达知识,版权归原作者所有,如涉及作品版权问题,请联系我进行删除

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码