//IDE: Visual Studio 2008
#include "stdafx.h"
#include <string.h>
const int nmemb = 3;
struct test
{
char name[20];
int size;
}s[nmemb];
void set_s(int x, char* y){
strcpy(s[x].name, y);
s[x].size = strlen(y);
}
int _tmain(int argc, _TCHAR* argv[])
{
FILE * stream;
int i;
set_s(0,"Linux!");
set_s(1,"FreeBSD!");
set_s(2,"Windows2000.");
for(i=0;i<nmemb;i++)
printf("name[%d]=%-20s:size[%d]=%d\n",i,s[i].name,i,s[i].size);
//tmp为工程目录下手工建立的一个文件夹
stream = fopen("./tmp/testFile","w");
if(stream == NULL){
printf("fopen (to write) failed...\n");
return -1;
}
fwrite(s,sizeof(struct test),nmemb,stream);
fclose(stream);
stream = fopen("./tmp/testFile","r");
if(stream == NULL){
printf("fopen (to read) failed...\n");
return -1;
}
fread(s,sizeof(struct test),nmemb,stream);
fclose(stream);
for(i=0;i<nmemb;i++)
printf("name[%d]=%-20s:size[%d]=%d\n",i,s[i].name,i,s[i].size);
return 0;
}