《文件篇》读写txt

发布时间 2023-11-16 14:37:58作者: Fusio

stdio.h

fopen(),打开文件

fopen(const char * filename, const char * mode)

其中mode:

"r",read: 为输入操作打开文件,文件必须存在。
"w",write: 为输出操作创建一个空文件,如果文件已存在,则将已有文件内容舍弃,按照空文件对待。
"a",append: 为输出打开文件,输出操作总是再文件末尾追加数据,如果文件不存在,创建新文件。
"r+",read/update: 为更新打开文件(输入和输出),文件必须存在
"w+",write/update: 为输入和输出创建一个空文件,如果文件已存在,则将已有文件内容舍弃,按照空文件对待。
"a+",append/update: 为输出打开文件,输出操作总是再文件末尾追加数据,如果文件不存在,创建新文件。

其中返回值:

如果文件成功打开,返回指向FILE对象的指针,否则返回NULL;

实例:

/* fopen example */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  pFile = fopen ("myfile.txt","w");
  if (pFile!=NULL)
  {
	fputs ("fopen example",pFile);
	fclose (pFile);
  }
  return 0;
}

fprintf(),输出到文件

#include <stdio.h>
int fprintf( FILE *stream, const char *format, ... );

返回值:

若成功则返回输出字符数,若输出出错则返回负值。

程序示例:

#include <stdio.h>
#include <process.h>

  FILE *stream;
  void main( void )
  {
	int i = 10;
	double fp = 1.5;
	char s[] = "this is a string";
	char c = '\n';
	stream = fopen( "fprintf.out", "w" );
	fprintf( stream, "%s%c", s, c );
	fprintf( stream, "%d\n", i );
	fprintf( stream, "%f\n", fp );
	fclose( stream );
	system( "type fprintf.out" );
   }

屏幕输出:

  this is a string
  10
  1.500000

fseek(),按偏移量移动文件指针的位置

#include<stdio.h>
int fseek(FILE *stream, long int offset, int whence)
// 第一个参数stream为文件 指针
// 第二个参数offset为 偏移量 ,正数表示正向偏移,负数表示负向偏移
// 第三个参数origin设定从文件的哪里
// 开始偏移,可能取值为:SEEK_CUR、 SEEK_END 或 SEEK_SET
// SEEK_SET: 文件开头,SEEK_CUR: 当前位置,SEEK_END: 文件结尾
// 其中SEEK_SET,SEEK_CUR和SEEK_END依次为0,1和2.

实例:

fseek(fp,100L,0);把文件内部 指针 移动到离文件开头100字节处;
fseek(fp,100L,1);把文件内部 指针 移动到离文件当前位置100字节处;
fseek(fp,-100L,2);把文件内部 指针 退回到离文件结尾100字节处。
seek(fp, 0L, SEEK_END);解释:文件指针定位到文件末尾,偏移0个字节
fseek(fp,50L,0);或fseek(fp,50L,SEEK_SET);解释:其作用是将位置指针移到离文件头50个字节处

ftell(),返回文件指针的位置

原文链接:https://www.cnblogs.com/dylancao/p/10497227.html

long int ftell(FILE *stream)

实例:

#include <stdio.h>

void main() {
	FILE *fp;
	int length;

	fp = fopen("file.txt", "r");
	// 可以使用SEEK_END常量来将文件指针移动文件末尾。
	fseek(fp, 0, SEEK_END);

	length = ftell(fp);

	fclose(fp);
	printf("Size of file: %d bytes", length);

}

这里file.txt的格式如下:

0x12,0x32

输出结果:

Size of file: 11 bytes

文件内容如下时,

0x12,0x32,3

输出结果如下:

Size of file: 13 bytes

feof(),检测流上的文件结束符,如果文件结束,则返回非0值,否则返回0