#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#define MAX 1024
#define PATH "C:\\Users\\user\\Desktop\\test5\\test.txt"
void main()
{
FILE* fp;
int i=1,num;
fp = fopen(PATH, "w+");
string strFin,strbuf1;
if(NULL == fp)
{
perror("fopen error!");
}
char buf[MAX] = {0};//定义一个缓存空间
char *p = buf;
printf("%d, %d", sizeof(buf), sizeof(p));
memset(buf, 0, sizeof(buf));
for(;i<=20;i++)
{
memset(buf, 0, sizeof(buf));
sprintf(buf, "我是%d号\n", i);
cout << buf << endl;
int iNum = fwrite(buf, strlen(buf), 1, fp);
if(iNum == 0)
{
cout << "error" << endl;
break;
}
}
//fclose(fp);
//fp = fopen(PATH, "a+");
fseek(fp,0,SEEK_SET);//或者fseek(fp,0,0);复位文件流指针到文件开头
cout << "fread()" << endl;
char buf1[MAX] = {0};
do{
//num = fread(buf1, sizeof(buf1), 1, fp);
memset(buf1, 0, sizeof(buf1));
cout << "BUF1:"<< buf1 << endl<<endl;
num = fread(buf1, 1, 128, fp);
if(num != 0)
{
//memset(&strbuf1, 0, sizeof(strbuf1));
//strbuf1 = buf1;
//strFin += strbuf1;
strFin += buf1;
cout << "节点:"<< buf1 << endl<<endl;
}
}while(num != 0);
cout << "最终:" << endl << strFin.c_str() << endl;
//cout << "最终:" << endl << strFin.c_str() << endl;
fclose(fp);//结束一定要关闭文件流指针,否者会造成内存泄漏
}
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#define MAX 1024
#define PATH "C:\\Users\\user\\Desktop\\test5\\test.txt"
void main()
{
FILE* fp;
int i=1,num;
fp = fopen(PATH, "w+");
string strFin,strbuf1;
if(NULL == fp)
{
perror("fopen error!");
}
char buf[MAX] = {0};//定义一个缓存空间
char *p = buf;
printf("%d, %d", sizeof(buf), sizeof(p));
memset(buf, 0, sizeof(buf));
for(;i<=20;i++)
{
memset(buf, 0, sizeof(buf));
sprintf(buf, "我是%d号\n", i);
cout << buf << endl;
int iNum = fwrite(buf, strlen(buf), 1, fp);
if(iNum == 0)
{
cout << "error" << endl;
break;
}
}
//fclose(fp);
//fp = fopen(PATH, "a+");
fseek(fp,0,SEEK_SET);//或者fseek(fp,0,0);复位文件流指针到文件开头
cout << "fread()" << endl;
char buf1[MAX] = {0};
do{
//num = fread(buf1, sizeof(buf1), 1, fp);
memset(buf1, 0, sizeof(buf1));
cout << "BUF1:"<< buf1 << endl<<endl;
num = fread(buf1, 1, 128, fp);
if(num != 0)
{
//memset(&strbuf1, 0, sizeof(strbuf1));
//strbuf1 = buf1;
//strFin += strbuf1;
strFin += buf1;
cout << "节点:"<< buf1 << endl<<endl;
}
}while(num != 0);
cout << "最终:" << endl << strFin.c_str() << endl;
//cout << "最终:" << endl << strFin.c_str() << endl;
fclose(fp);//结束一定要关闭文件流指针,否者会造成内存泄漏
}