文件操作 及文件指針移動 rewind ftell

文件使用之後一定要關閉,否則將不能正確顯示內容.fwrite:讀入兩個學生信息然後用fwrite存入文件

fread:用fread從文件中讀出學生信息。

fwrite.c

#include <stdio.h>
#define SIZE 2
struct student_type
{
  char name[10];
  int num;
  int age;
  char addr[10];
}stud[SIZE];


void save()
{
  FILE *fp;
  int i;
  if((fp=fopen("stu_list","wb"))==NULL)
  {
    printf("cant open the file");
    exit(0);
  }
  for(i=0;i<SIZE;i++)
  {
    if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
    printf("file write error\n");
  }
  fclose(fp);
}
main()
{
int i;
for(i=0;i<SIZE;i++)
{
scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
save();
}
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
}

fread.c

#include <stdio.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[10];
}stud[SIZE];
void read()
{
FILE *fp;
int i;
if((fp=fopen("stu_list","rb"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
main()
{

int i;
read();
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
printf("\n");
}
}

在C語言中進行文件操作時,我們經常用到fread()和fwrite(),用它們來對文件進行讀寫操作。下面詳細紹一下這兩個函數的用法。

我們在用C語言編寫程序時,一般使用標準文件系統,即緩衝文件系統。系統在內存中爲每個正在讀寫的文件開闢“文件緩衝區”,在對文件進行讀寫時數據都經過緩衝區。要對文件進行讀寫,系統首先開闢一塊內存區來保存文件信息,保存這些信息用的是一個結構體,將這個結構體typedef爲FILE類型。我們首先要定義一個指向這個結構體的指針,當程序打開一個文件時,我們獲得指向FILE結構的指針,通過這個指針,我們就可以對文件進行操作。例如:

#i nclude <stdio.h>

#i nclude <string.h>

int main()

{

FILE *fp;

char buffer[100] = "This is a test";

if((fp = fopen("c:\\example.txt", "w")) == 0)

{

printf("open failed!");

exit(1);

}

fwrite(buffer, 1, strlen("This is a test"), fp);

fclose(fp);

return 0;

}

通過以上代碼,我們就在c盤的根目錄下建立了一個名爲example擴展名爲.txt的文件,我們打開可以看到上面寫上了This is a test。當我們對它將它讀出時,用如下代碼:

#i nclude <stdio.h>

#i nclude <mem.h>

int main()

{

FILE *fp; int len;

char buffer[100];

if((fp = fopen("c:\\example.txt", "r")) == 0)

{

printf("open failed!");

exit(1);

}

fseek(fp, 0L, SEEK_END);

len = ftell(fp);

rewind(fp);

fread(buffer, 1, len , fp);

printf("%s",buffer);

fclose(fp);

getch();

return 0;

}

可以看到,當我們使用memset了以後,讀出了一大堆亂碼,這是爲什麼呢?原因是我們在fwrite函數時寫入的字節數是用strlen求得的,也就是說字符串最後的'\0'並沒有寫到文件中去。所以我們從文件中讀到buffer中時也自然沒有'\0',因爲buffer中的數是隨機的,除非buffer中最後一個字符的下一個數恰好隨機到0(可能性很小,這裏用memset將它排除),否則以%s將buffer中的字符輸出時遇不到0,所以亂碼產生。解決的辦法有很多,你可以在向文件寫數據時多寫入一個字節,系統會自動寫入0,fwrite(buffer, 1, strlen("This is a test")+1, fp);這樣讀出時最後就有一個0了。或者讀出操作完成後,在最後一個字符後面補上一個0:buffer[len] = 0;這樣問題也可得到解決。


C++文件操作: http://www.cnblogs.com/kzloser/archive/2012/07/16/2593133.html

C/C++文件輸入輸出操作——FILE*、fstream、windowsAPI http://hi.baidu.com/andywangcn/item/cb3e9785d6c124caee083ddb

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章