c語言-檔案io
阿新 • • 發佈:2019-02-01
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
FILE *p = fopen("D:\\study\\a.txt", "w");
fputs("hello world", p);
fputs("hello world", p);
fclose(p);
return 0;
}
判斷檔案是否成功開啟的常用方法
if((fp=fopen("D:\\study\\a.txt","w"))==NULL)
{
printf("cant open the file" );
exit(0);
}
copy一個二進位制檔案;(fread(),fwrite())
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include <time.h>
int main()
{
char buf[4096];
FILE *p1 = fopen("D:\\study\\a.zip", "rb");
FILE *p2 = fopen("D:\\study\\b.zip", "wb");
while (!feof(p1))
{
memset (buf, 0, sizeof(buf));
size_t res=fread(buf, sizeof(char), sizeof(buf), p1);
fwrite(buf, sizeof(char), res, p2);
}
fclose(p1);
fclose(p2);
return 0;
}
獲取檔案基本資訊(stat() )
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include <sys/stat.h>
int main()
{
struct stat buf;//需要定義結構體 struct stat buf
stat("D:\\study\\a.zip", &buf);
printf("file size =%d\n", buf.st_size);//輸出檔案大小
return 0;
}
統計程式消耗時間(clock())
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "time.h"
int main()
{
clock_t start_t = clock();
程式碼塊
clock_t end_t = clock();
printf("%d\n",(end_t - start_t));
return 0;