
- C语言--文件 *** 作
- 一、*包括:*``fgetc`` ``fputc`` ``fgets`` ``fputs`` ``fopen`` ``fclose`` 的使用
- 运行结果:
- 二、``fread`` 和 ``fwrite``
#include运行结果:fputc1() { FILE* pf = fopen("test1.txt", "w"); ' //以写的模式打开一个文件test1.txt ' if (pf == NULL) { perror("fopen"); exit(1); } fputc('x', pf); ' //写入字符'x' 'w' 'p' fputc('w', pf); fputc('p', pf); fclose(pf); ' //关闭文件 ' pf = NULL; } fgetc1() { FILE* pf = fopen("test1.txt", "r"); if (pf == NULL) { perror("fopen"); exit(1); } for (int i = 0; i < 3; i++) { printf("%cn", fgetc(pf)); } fclose(pf); pf = NULL; } fputs1() { FILE* pf = fopen("test1.txt", "w"); if (pf == NULL) { perror("fopen"); exit(1); } fputs("xwp is handsome", pf); fputs("Yeah!n", pf); fputs("I agree you", pf); fclose(pf); pf = NULL; } fgets1() { FILE* pf = fopen("test1.txt", "r"); if (pf == NULL) { perror("fopen"); exit(1); } char arr1[40] = { 0 }; fgets(arr1, 40, pf); puts(arr1); char arr2[20] = { 0 }; fgets(arr2, 20, pf); puts(arr2); fclose(pf); pf = NULL; } int main() { fputc1(); fgetc1(); fputs1(); fgets1(); return 0; }
二、fread 和 fwrite创建了一个test1.txt文件,内容如下:
fseek ftell rewind的使用示例
//fread fwrite fseek ftell rewind
//fwrite
struct S
{
char arr[10];
int a;
float f;
};
void fwrite1()
{
struct S sarr[] = { {"xpwhs", 25, 25.05f},
{"yzmhc", 25, 25.5f},
{"I agree", 66, 66.66} };
FILE* pf = fopen("test.dat", "wb");
if (pf == NULL)
{
perror("fopen");
fputs("FILE ERROR", stderr);
}
fwrite(sarr, sizeof(struct S), 3, pf);
fclose(pf);
pf = NULL;
}
//fread
void fread1()
{
FILE* pf = fopen("test.dat", "rb");
if (pf == NULL)
{
perror("fopen");
fputs("FILE ERROR", stderr);
exit(1);
}
' //计算文件的大小,对应的开辟内存空间 '
fseek(pf, 0, SEEK_END);
long lsize = ftell(pf);
rewind(pf);
struct S* buffer = (struct S*)malloc(lsize);
if (buffer == NULL) { fputs("malloc error", stderr); exit(2); }
fread(buffer, sizeof(struct S), 3, pf);
fclose(pf);
pf = NULL;
' //显示buffer内容 '
for (int i = 0; i < 3; i++)
{
printf("%s %d %fn", buffer[i].arr, buffer[i].a, buffer[i].f);
}
free(buffer);
buffer = NULL;
}
int main()
{
fwrite1();
fread1();
return 0;
}
写入的test.dat如下所示:
显示的内容:
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)