如果您想以 ASCII 格式存储,我的建议是按字符输入。
像这样
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define msize 4096
struct memory {
char a[msize];
};
/*
m.a[0]=250; // temperature value of 25,0
m.a[4]=01; // heater status OFF
m.a[8]=240; // temperature value of 24,0
m.a[12]=00; // heater status ON
m.a[16]=220;// temperature value of 22,0
m.a[20]=00; // heater status ON
*/
int read(struct memory *m){
char inputbuff[4+1];
int i=0;
memset(m->a, ' ', sizeof(m->a)/sizeof(m->a[0]));//initialize by space
while(i<msize/(4+4)){
printf("input temperature value e.g.25,0 : 250(and enter)\n");
fgets(inputbuff, sizeof(inputbuff), stdin);
strncpy(m->a + i*4, inputbuff, 3);
//i+=1;
printf("input heater status ON or OFF e.g.ON : 00 , OFF : 01(and enter)\n");
fgets(inputbuff, sizeof(inputbuff), stdin);
strncpy(m->a + (i+1)*4, inputbuff, 2);
i += 1;
printf("continue input? (y or n) : ");
fgets(inputbuff, sizeof(inputbuff), stdin);
if(*inputbuff=='n' || *inputbuff=='N'){
break;
}
}
return i;
}
int main(void){
struct memory m;
read(&m);
{
//check print
m.a[msize-1]='\0';
printf("%s\n", m.a);
}
return 0;
}
添加更多
#include <stdio.h>
#include <string.h>
#define msize 4098
int *storeInt(void *address){
int *ip =(int*)address;
*ip = 777;//ip[0]=777;ip[1]=888;...
return ip;
}
char *storeChars(void *address){
char *cp =(char*)address;
strcpy(cp, "hello");
return cp;
}
void dump(void *address, size_t length){
unsigned char *cp = (unsigned char*)address;
size_t i;
for(i=0;i<length;++i){
if(i % 16 == 0) printf("\n");
printf("%02X ", *cp++);
}
}
int main(void){
static char memory[msize];//create a static memory of a particular size
char *block1, *block2;
block1 = &memory[0];
block2 = &memory[1024*2];//split a virtual
int *ip;
ip=storeInt(block1);//store some values in the memory
printf("%d\n", *ip);//read the values from the memory
char *cp;
cp=storeChars(block2);//set hello\0
printf("%s\n", cp);//say hello
char ascValue[12];
int value = *ip;//777
//convert "value of int" to Ascii
sprintf(ascValue, "%d", value);
//Display it
printf("value is %s\n", ascValue);
dump(block1, 8);
dump(block2, 8);
return 0;
}