- 论坛徽章:
- 14
|
你的代码中有很多低级错误,另外,如果这道题用C++ template来做的话,就会很优雅。
当然,听hellioncu的,用protobuf是正道(虽然我没用过)- #include <stdio.h>
- #include <string.h>
- void foo_write_int( char* p, size_t* off, int n )
- {
- *(int*)(p+*off) = n;
- *off += sizeof(int);
- }
- void foo_read_int( const char* p, size_t* off, int* n )
- {
- *n = *(int*)(p+*off);
- *off += sizeof(int);
- }
- void foo_write_string( char* p, size_t* off, const char* s )
- {
- size_t len = strlen(s);
- *(size_t*)(p+*off) = len;
- *off += sizeof(size_t);
- memcpy( p+*off, s, len );
- *off += len;
- }
- void foo_read_string( const char* p, size_t* off, char* s )
- {
- size_t len = *(size_t*)(p+*off);
- *off += sizeof(size_t);
- memcpy( s, p+*off, len );
- *off += len;
- s[len] = '\0';
- }
- int main( void )
- {
- char line[100];
- {
- int a = 5;
- int b = 5000;
- const char* c = "Your are man";
- size_t off = 0;
- foo_write_int( line, &off, a );
- foo_write_int( line, &off, b );
- foo_write_string( line, &off, c );
- }
- {
- int a;
- int b;
- char c[20];
- size_t off = 0;
- foo_read_int( line, &off, &a );
- foo_read_int( line, &off, &b );
- foo_read_string( line, &off, c );
- printf( "%d, %d, %s\n", a, b, c );
- }
- return 0;
- }
复制代码 |
|