12 10 文件行读取
memset(buf, 0, 1024);//防止上一次污染下一次
二进制文件有-1,所以不能用EOF
feof可以判断二进制和文本文件,!0结尾;0,未结尾
01 写
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char* p = "没内鬼,可以交易\n";
FILE* fp = fopen("d.txt", "w");
if (!fp)
{
return -1;
}
fputs(p, fp);
fclose(fp);
system("pause");
}
02 行读
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//读,打印
void main()
{
FILE* fp = fopen("d.txt", "r");
if (!fp)
{
return -1;
}
char buf[1024];//1024B
fgets(buf, 1024, fp);
printf("%s", buf);
fclose(fp);
system("pause");
}
03 读一行,重置buff,再读一行
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//读一行,重置buff,再读一行
void main()
{
FILE* fp = fopen("d.txt", "r");
if (!fp)
{
return -1;
}
char buf[1024];//1024B
fgets(buf, 1024, fp);
printf("%s", buf);
memset(buf, 0, 1024);//重置buff
fgets(buf, 1024, fp);
printf("%s", buf);
fclose(fp);
system("pause");
}
04 读n个字节
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//每次读5个
void main()
{
FILE* fp = fopen("d.txt", "r");
if (!fp)
{
return -1;
}
char buf[7];
fgets(buf, 7, fp);//汉字=2B,\0=1B
printf("%s\n", buf);
memset(buf, 0, 7);//重置buff
fgets(buf, 7, fp);
printf("%s\n", buf);
fclose(fp);
system("pause");
}
05 堆上开空间读取 malloc feof
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//5
void main()
{
FILE* fp = fopen("d.txt", "r");
if (!fp)
{
return -1;
}
char* buf = malloc(sizeof(char) * 1024);//堆上开一块1KB的空间
while (feof(fp) == 0)
{
memset(buf, 0, 1024);
fgets(buf, 1024, fp);
printf("%s", buf);
}
free(buf);
fclose(fp);
system("pause");
}