I have a txt
file, content of file is :
0x1a,0x2b,0xff,0x99,0x55
I need to store all this value into :
unsigned char tempArray[10]={0xaa,0xbb,0xcc,0xdd,0xee,0x00,0x00,0x00,0x00,0x00}.
is there any solution so that my :
tempArray[]= {0xaa,0xbb,0xcc,0xdd,0xee,0x1a,0x2b,0xff,0x99,0x55}.
need to store values from .text file into specific location of array USING c / cpp only.
Thanking you in anticipation of favorable replies. :)
EDIT
'till now i am reading 1.txt
file character by character. variable ch
store the the curent value, i am trying to store the ch
value to ch2*
later copy to array.
Te code below works fine for reading value but shows segmentation fault
when ch2
came in picture.
unsigned char tempArray[10]={0xaa,0xbb,0xcc,0xdd,0xee,0x00,0x00,0x00,0x00,0x00};
int main()
{
char ch,i=0;
FILE *fp;
char *ch2=NULL;
fp = fopen("1.txt","r"); // read mode
if( fp == NULL )
{
printf("err");
return 0;
}
printf("The contents of file are :\n");
while(( ch = fgetc(fp)) != EOF )
{
if(ch==',')
{
printf(" ");
}
else
{
printf("%c",ch);
//sprintf(ch2,"%c",ch2);
//printf("\tch2 :: %s",ch2);
}
}
i++;
fclose(fp);
return 0;
}
Using your code you can simply code:
uint32_t index = 0;
while(( ch = fgetc(fp)) != EOF )
{
if(ch==',')
{
printf(" ");
}
else
{
printf("%c",ch);
tempArray[index] = ch;
if ( tempArray < (sizeof(tempArray)/sizeof(tempArray[0])) )
{
index++;
}
}
}
The segmentation fault you are seeing, I guess, is caused by
char *ch2=NULL;
After that you must allocate space where byte read will be placed. You can use malloc
to do that.
char *ch2=malloc(size_of_you_buffer*sizeof(unsigned char);
Where size_of_you_buffer
must be set accordingly to your needs.
unsigned char tempArray[]=
{
#include "file.txt"
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.