您的位置:首页 > 运维架构

20121011总结——fopen _ fread _ fwrite _ fread

2013-09-18 21:12 225 查看
#include <stdio.h> // fopen, fwrite, fread, fclose
#include <string.h> // memset
#include <errno.h> // perror
#include <stdlib.h> // exit
#include <unistd.h> // EXIT_FAILURE

/*function: 打开文件写个hello,然后追加写个_word,然后读出来 */
int main()
{
FILE *fp;
char buf[20];
memset(buf, 0, 20);
char *pt = "hello";
char *pq = "_world";

/******************写入文件***************************/
fp = fopen("haha.txt", "w");
if (fp == NULL) {
perror("fopen error\n"); // head is <errno.h>
exit(EXIT_FAILURE); // exit ->head is <stdlib.h> EXIT_FAILURE ->head is <unistd.h>
}
int ret = fwrite(pt, 1, 5, fp);
if (ret == 0) {
perror("fwrite error\n");
exit(EXIT_FAILURE);
}
fclose(fp);

/******************添加文件****************************/
fp = fopen("haha.txt", "a");
ret = fwrite(pq, 1, 7, fp);
if (ret == 0) {
perror("fwrite error\n");
exit(EXIT_FAILURE);
}
fclose(fp);

/*********************读文件**************************/
fp = fopen("haha.txt", "r");
if (fp == NULL) {
perror("fopen error\n");
exit(EXIT_FAILURE);
}
ret = fread(buf, 1, 14,fp);
fclose(fp);

printf("%s\n",buf);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: