有什么方法可以将其构造为文件并使用fwrite和fread读取
我尝试了几种方法,但没有任何反应
struct Register{
user[20][20];
pass[20][20];
} x[10];
答案 0 :(得分:0)
以下建议的代码可能是您想要的:
#include <stdio.h>
#include <stdlib.h>
// to avoid using 'magic' numbers
#define NUM_STRUCTS 10
#define MAX_USERS 20
#define MAX_USER_LEN 20
#define MAX_PASSS 20
#define MAX_PASS_LEN 20
struct Register
{
char user[ MAX_USERS ][ MAX_USER_LEN ];
char pass[ MAX_PASSS ][ MAX_PASS_LEN ];
};
int main( void )
{
struct Register x[ NUM_STRUCTS ];
// initialize structs here, then
FILE *fp = fopen( "fileContainingStructs", "w" );
if( !fp )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
size_t numStructs =
fwrite( x, sizeof( struct Register ), NUM_STRUCTS, fp );
if( numStructs != NUM_STRUCTS )
{
perror( "fwrite failed" );
fclose( fp );
exit( EXIT_FAILURE );
}
// implied else, fwrite successful
fclose( fp );
}