关于文件读写的几点学习记录

1. 各函数的简单理解

2. 写文件过程中遇到的坑

下面这段代码是找出1~10000之间的素数并保存到文件中。在使用fscanf读取文件的过程中我遇到了几个问题:
1、空文件时如何判断文件结束(文本文件可以直接用feof,对于二进制文件而言可以int ch,读入数据前令ch=fgetc(fp),若ch=EOF,则文件为空)
2、在使用fscanf读数据时发现它的返回值总为-1,即没有分配给它数据,后来发现要再次打开文件,“w”只写,再用“r”打开一遍就行了。
3、fscanf遇到空格、换行停止,坑的一批
3、这代码有问题关于文件读写的几点学习记录

#include <stdio.h>
#include <stdlib.h>
int isprime(int n);
int main(){
	FILE *fp;
	if((fp=fopen("file_date.txt","w"))==NULL){
		printf("Can not open the file!\n");
		exit(0);
	}
	int i,count=0;
	for(i=1;i<10000;i++){
		if(isprime(i)!=-1){
			count++;
			if(count%10!=0)fprintf(fp,"%d\t",i);
			else fprintf(fp,"%d\n",i);
		}
	}
	int n;
	fp=fopen("file_date.txt","rb");
	while(!feof(fp)){
		fscanf(fp,"%d\t",&n);
		printf("%d\n",n);
	}
	fclose(fp);
	return 0;
}
int isprime(int n){
	int i,ret=-1;
	if(n==1)return -1;
	if(n==2||n==3)return 1;
	for(i=2;i<=n/2;i++){
		if(n%i==0)return ret;
	}
	return 1;
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-08
  • 2022-12-23
  • 2021-10-15
  • 2021-11-20
  • 2021-12-05
猜你喜欢
  • 2021-07-14
  • 2021-12-11
  • 2021-06-01
  • 2021-10-28
  • 2021-09-07
  • 2022-01-21
  • 2022-12-23
相关资源
相似解决方案