64,648
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
/* 打开模式介绍
"r" 只读,文件必须存在
"r+", 读写,文件必须存在
"w" 只写,不管文件是否存在,都创建新文件(同时清空原内容)
"w+", 读写,不管文件是否存在,都创建新文件(同时清空原内容)
"a" 追加, 文件不存在会创建新文件,存在则打开.只能追加
"a+", 读+追加,文件不存在会创建新文件,存在则打开.可以调整文件指针来读取数据,但是写入数据会自动跳到文件最后进行追加
*/
FILE *pFile;
pFile = fopen("a.txt", "w");
fprintf(pFile, "fclose example");
rewind(pFile);
fputs("1234567890 hello world 你好啊\nsecond line\ngo\n", pFile);
fclose(pFile);
// 以读写方式打开一个文件
pFile = fopen("a.txt", "a+"); //1,打开一个文件,不存在在创建
if (pFile == NULL)
{
puts("fopen error\n");
}
else
{
//pFile = freopen("a.txt", "r+", pFile); //重新打开这个文件,以r+(可读写)方式打开
fclose(pFile);
pFile = fopen("a.txt", "r+");
if (pFile == NULL)
{
puts("freopen error\n");
}
else
{
char buff[1024] = {0};
fgets(buff, 1023, pFile); //遇到文件结束符或者换行符就会停止读取.
puts(buff);
}
}
//rewind(pFile);
int pos = ftell(pFile);
fpos_t fpos;
fgetpos(pFile, &fpos);
if (pos == EOF)
{
puts("ftell is end of file\n");
}
fseek(pFile, 0, SEEK_CUR); //SEEK_SET, SEEK_CUR, SEEK_END.....注意,注释了这一句后,后面的fputs就没有写到文件中去.
fputs("new fputs", pFile);
fputc('A', pFile);
fflush(pFile);
printf("\n\nfgetc测试\n");
rewind(pFile); //移动文件指针到文件头
int ch;
while (EOF != (ch=fgetc(pFile)))
{
putchar(ch);
}
struct stTest
{
int a;
char c;
double d;
};
stTest st = {1, 'C', 3.65};
fseek(pFile, 0, SEEK_END);
fwrite(&st, sizeof(st), 1, pFile);
memset(&st, 0, sizeof(st));
fseek(pFile, -sizeof(st), SEEK_END);
fread(&st, sizeof(st), 1, pFile);
printf("%d, %c, %Lf", st.a, st.c, st.d);
fclose(pFile);
system("pause");
}
void test1()
{
FILE *pFile;
pFile = fopen("a.txt", "w");
fputs("1234567890 hello world 你好啊\nsecond line\ngo\n", pFile);
fclose(pFile);
pFile = fopen("a.txt", "r+");
char buff[1024] = {0};
fgets(buff, 1023, pFile); //遇到文件结束符或者换行符就会停止读取.
puts(buff);
fseek(pFile, 0, SEEK_CUR); //SEEK_SET, SEEK_CUR, SEEK_END.....注意,注释了这一句后,后面的fputs就没有写到文件中去.
fputs("new fputs", pFile);
fputc('A', pFile);
fflush(pFile);
rewind(pFile); //移动文件指针到文件头
int ch;
while (EOF != (ch=fgetc(pFile)))
{
putchar(ch);
}
fclose(pFile);
system("pause");
}
简化版本,大家帮忙看看问题啊