C语言进阶:文件操作_extern _armabi

Return Value
This function returns the character written. 

Parameters
1. c - Character to be written
2. stream - Pointer to FILE structure

Remarks
This function writes the single character c to a file at the position pointed by the associated file position pointer (if defined) and advances the pointer appropriately(适当). 

int fgetc (FILE\* stream);

Return Value
fgetc return the character read as an int or return EOF to indicate an error or end of file. 

Parameter
stream - Pointer to FILE structure

Remarks
This function reads a single character from the current position of a file; The function then increments(递增) the associated file pointer (if defined) to point to the next character.

fputc将字符c放到文件指针stream所指向的文件中。

fgetc返回文件指针所指向的字符。

函数用法
  • fputc每写入一个字符文件指针就向后移动一个字符的位置。fgetc每读取一个字符文件指针就向后移动一个字符的位置。
  • fputc适用于所有输出流,可以输出到任意设备上。fgetc同样适用于所有输入流,可以从任意设备上读取数据。
int main() {
	FILE\* pf = fopen("data.txt", "w");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	fputc('a', pf);
	fputc('b', pf);
	fputc('c', pf);	
	fclose(pf);
	pf = NULL;
	return 0;
}
int main() {
	FILE\* pf = fopen("data.txt", "r");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	int ch = fgetc(pf);
	printf("%c ", ch);
	ch = fgetc(pf);
	printf("%c ", ch);
	ch = fgetc(pf);
	printf("%c ", ch);
	fclose(pf);
	pf = NULL;
	return 0;
} 

//标准输出流
fputc('b', stdout);
fputc('i', stdout);
fputc('t', stdout);
//标准输入流
printf("%c\n", fgetc(stdin));
printf("%c\n", fgetc(stdin));
printf("%c\n", fgetc(stdin));

字符串输入输出 fputs&fgets
函数声明
int fputs (const char\* string, FILE\* stream);

Return Value
This function returns a nonnegative(非负) value if it is successful. On an error, fputs returns EOF.

Parameters
1. string - Output string
2. stream - Pointer to FILE structure

Remarks
This function copies string to the output stream at the current position.

char\* fgets (char\* string, int n, FILE\* stream);

Return Value
This function returns string. NULL is returned to indicate an error or an end-of-file condition.

Parameters
1. string - Storage location for data
2. n - Maximum number of characters to read
3. stream - Pointer to FILE structure

Remarks
The fgets function reads a string from the input stream argument and stores it in string. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in string is appended with a null character. The newline character, if read, is included in the string. 

fputc将字符串string放到文件指针stream所指向的文件中。

fgetsstream文件中指向的字符串的前n-1个字符放入string中,并以返回值的形式返回。

函数用法
  • fputs一次写入一行,若需换行可以加上\n,文件指针移动到末尾。
  • fgets每次只读取规定字符数

n

1

n-1

n−1 个字符最后第

n

n

n 个字符为\0作为字符串结束标志。

  • fputs适用于所有输出流,可以输出到任意设备上。fgets同样适用于所有输入流,可以从任意设备上读取数据。
int main() {
	FILE\* pf = fopen("data.txt", "w");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	fputs("hello world!\n", pf);
	fputs("hello bit!\n", pf);
	fclose(pf);
	pf = NULL;
	return 0;
}
int main() {
	FILE\* pf = fopen("data.txt", "r");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	char arr[20] = { 0 };
	fgets(arr, 5, pf);
	printf("%s\n", arr);
	fgets(arr, 5, pf);
	printf("%s\n", arr);
	fclose(pf);
	pf = NULL;
	return 0;
}

格式化输入输出 fprintf&pscanf
函数声明
int fprintf (FILE\* stream, const char\* format [, argument ]...);

Return Value
fprintf returns the number of bytes written. This function returns a negative value instead when an output error occurs. 

Parameters
1. stream - Pointer to FILE structure
2. format - Format-control string
3. argument - Optional arguments

Remarks
fprintf formats(格式化) and prints all characters and values to the output stream. Each argument(参数) is converted(转换) and output according to the corresponding format specification(规范). For fprintf, the format argument has the same syntax(语法) that it has in printf.

int fscanf (FILE\* stream, const char\* format [, argument ]...);

Return Value
This function returns the number of fields(字段数) successfully converted(转化) and assigned(分配); 

Parameters
1. stream - Pointer to FILE structure
2. format - Format-control string
3. argument - Optional arguments

Remarks
The fscanf function reads data from the current position of stream into the locations given by argument (if any). It has the same form and function as the format argument for scanf;

fprintf,fscanf是以格式化的形式,例如:"%d,%f",a,f,输出输入到所有输入输出流。

函数用法
  • fprintf,fscanf和 printf,scnaf 的参数差别仅是前面带有文件指针pf,故写好 printf,scanf 的形式再在参数列表最前添上文件指针pf。如:
struct S {
	int a;
	char c;
	double d;
};
int main() {
	FILE\* pf = fopen("data.txt", "w");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	struct S s = { 100,'w',3.14 };
	fprintf(pf, "%d %c %lf", s.a, s.c ,s.d);

	return 0;
}
int main() {
	FILE\* pf = fopen("data.txt", "r");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	struct S s = { 0 };
	fscanf(pf, "%d %c %lf", &s.a, &s.c, &s.d);
	printf("%d %c %lf", s.a, s.c, s.d);
	return 0;
}

  • fprintf适用于所有输出流,可以输出到任意设备上。fscanf同样适用于所有输入流,可以从任意设备上读取数据。

以上有适用于单个字符的,适用于字符串的以及适用于任意格式的字符,字符串,格式化输入输出函数。但都是文本形式的输入输出函数,接下来的是以二进制的形式的输入输出函数。

二进制输入输出 fwrite&fread
函数声明
size\_t fwrite (const void\* buffer, size\_t size, size\_t count, FILE\* stream);

Return Value
fwrite returns the number of full items actually written.

Parameters
1. buffer - Pointer to data to be written(指向待写数据的指针)
2. size - Item size in bytes(元素宽度)
3. count - Number of items to be written(元素个数)
4. stream - Pointer to FILE structure(文件指针)

Remarks
The fwrite function writes up to count items, of size length each, from buffer to the output stream. The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written. 

size\_t fread (void\* buffer, size\_t size, size\_t count, FILE\* stream);

Return Value
fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. 

Parameters
1. buffer - Storage location for data
2. size - Item size in bytes
3. count - Maximum number of items to be read
4. stream - Pointer to FILE structure

Remarks
The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read.

函数用法
  • fwrite把从buffer位置的count个大小为size的元素以二进制的形式写入文件stream中。

  • fread把从文件stream的中count个大小为size的元素以二进制的形式读取到buffer中。

struct S {
	int a;
	char c[20];
	double d;
};
int main() {
	FILE\* pf = fopen("data.txt", "wb");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	struct S s = { 100,"yyx",3.14 };
	fwrite(&s, sizeof(s), 1, pf);
	return 0;
}
int main() {
	FILE\* pf = fopen("data.txt", "rb");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	struct S s = { 0 };
	fread(&s, sizeof(s), 1, pf);
	printf("%d %s %lf", s.a, s.c, s.d);
	return 0;
}

输入输出函数的对比
//1. 
scanf/fscanf/sscanf
//2. 
printf/fprintf/sprintf

函数名内容备注
scanf标准输入流(键盘)读取格式化的数据省略standard
fscanf所有输入流读取读取格式化数据f:file
sscanf字符串中读取格式化的数据s:string
printf将格式化的数据输出到标准输出流(屏幕)上省略standard
fprintf将格式化数据输出到所有输出流f:file
sprintf将格式化的数据输出到字符串s:string

int main() {
    //sprintf
    struct S s = { 100,"yyx",3.14 };
	char arr[20] = { 0 };
	sprintf(arr, "%d%s%lf", s.a, s.c, s.d);
	printf("%s\n", arr);
	//sscanf
	sscanf(arr, "%d %s %lf", &s.a, s.c, &s.d);
	printf("%d %s %lf", s.a, s.c, s.d);
	return 0;
}

sprintf把格式化的数据输出到字符串中,sscanf把字符串中的数据输入到程序(格式化形式读取)。

文件的随机读写

随机读写,即随意改变文件指针的位置进行自定义位置的读写。

更改文件指针 fseek
函数声明
int fseek (FILE\* stream, long offset, int origin);

Return Value
If successful, fseek returns 0. Otherwise, it returns a nonzero value.

Parameters
1. stream - Pointer to FILE structure
2. offset - Number of bytes from origin
3. origin - Initial position

Remarks
The fseek function moves the file pointer (if any) associated with stream to a new location that is offset bytes from origin. 

fseek通过文件指针距起始位置的偏移量来完成对文件指针的重定位。

函数用法
  • 起始位置origin可以传三种值:SEEK_SET,SEEK_END,SEEK_CUR,分别对应文件起始,文件末尾,文件当前位置。

  • 文件指针偏移量即两个指针相减的结果。输入输出函数也会影响文件指针当前的位置。

'f'相对于起始位置SEEK_SET的偏移量为4,相对于文件末尾SEEK_END的偏移量为-8。

  • fseek函数仅是重定位文件指针,不包含任何的输入输出语句。
int main()
{
	FILE\* pf = fopen("C:\\Users\\w3395\\Desktop\\data.txt", "r");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
    //读取字符
	printf("%c", fgetc(pf));//y
	fseek(pf, 1, SEEK\_SET);
	printf("%c", fgetc(pf));//o
	fseek(pf, 2, SEEK\_SET);
	printf("%c", fgetc(pf));//u
	fseek(pf, 3, SEEK\_SET);
	printf("%c", fgetc(pf));//r
	fseek(pf, -2, SEEK\_CUR);
	printf("%c", fgetc(pf));//u
	fseek(pf, -2, SEEK\_CUR);
	printf("%c", fgetc(pf));//o
	fseek(pf, -2, SEEK\_CUR);
	printf("%c", fgetc(pf));//y
    fclose(pf);
	pf = NULL;
	return 0;
}

定位文件指针 ftell
函数声明
long ftell (FILE\* stream);

Return Value
ftell returns the current file position.

Parameter
stream - Target FILE structure

Remarks
The ftell function gets the current position of the file pointer (if any) expressed as an offset relative to the beginning of the stream.

ftell以距起始位置的偏移量的形式返回当前文件指针的位置。

函数用法
int main()
{
	FILE\* pf = fopen("C:\\Users\\w3395\\Desktop\\data.txt", "r");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	fseek(pf, 3, SEEK\_SET);
	int ret = ftell(pf);
	printf("%d\n", ret);
    return 0;
}

重置文件指针 rewind
函数声明
void rewind (FILE\* stream);

Return Value
None

Parameter
stream - Pointer to FILE structure

Remarks
The rewind function repositions(重置) the file pointer associated with stream to the beginning of the file. 

函数用法
  • rewind将文件指针恢复初始状态。

文件结束的判断
输入函数返回值的判断

类似于oj题中,多次输入的方法,利用scanf的返回值进行判断:

while (scanf("%d", &n) != EOF)} {
    ;
}

由于在oj题中输入由系统控制(类似于读取文件),当读取结束时会返回EOF,所以在循环判断部分对scanf的返回值进行判断,可以达到多次读入的效果。

文件输入函数具有同样的特点,也可以利用其返回值进行判断,以达到循环读入的目的。

输入函数利用返回值判断
fgetc以整型的形式返回读到的字符,遇到错误或文件结束时返回EOF
fgets返回读到的字符串,遇到错误或文件结束时返回NULL
fscanf返回成功读到并转化的字段数,当小于规定字段数时读取失败,没有字段时返回0
fread返回实际读到的元素个数,若小于参数count则无可再读。

具体实现如下列代码:

//fgetc
int ch = 0;
while ((ch = fgetc(pf)) != EOF) {
    printf("%c ", ch);
}
//fgets
char arr[2][20] = { 0 };
while ((fgets(arr, 3, pf)) != NULL) {
    printf("%s\n", arr);
}
//fscanf
int ch = 0;
while (fscanf(pf, "%c", &ch) == 1) {
    printf("%c\n", ch);
}
//fread
int ch = 0;
while (fread(&ch, 1, 1, pf) == 1) {
    printf("%c\n", ch);
}

判断文件结束 feof

feof不是用于判断文件是否读取结束的。而是当文件读取结束时,用于判断结束的原因是遇到错误还是到达文件末尾的

函数声明
Return Value
feof returns a nonzero value after the first read operation that attempts to read past the end of the file. It returns 0 if the current position is not end of file. There is no error return.

函数用法
int main()
{
	FILE\* pf = fopen("data.txt", "r");
	if (pf == NULL) {
		perror("fopen");
		return -1;
	}
	int ch = 0;
	while ((ch = fgetc(pf)) != EOF) {
		printf("%c ", ch);
	}
	if (feof(pf)) {
		printf("\n%s\n", "end of file reached successfully");
	}
	if (ferror(pf)) {
		printf("\n%s\n", "unknowed error");
	}
	fclose(pf);
	pf = NULL;
	return 0;
}

  • feof:是当文件结束时,判断是否是遇到文件末尾而结束的。

写在最后

在结束之际,我想重申的是,学习并非如攀登险峻高峰,而是如滴水穿石般的持久累积。尤其当我们步入工作岗位之后,持之以恒的学习变得愈发不易,如同在茫茫大海中独自划舟,稍有松懈便可能被巨浪吞噬。然而,对于我们程序员而言,学习是生存之本,是我们在激烈市场竞争中立于不败之地的关键。一旦停止学习,我们便如同逆水行舟,不进则退,终将被时代的洪流所淘汰。因此,不断汲取新知识,不仅是对自己的提升,更是对自己的一份珍贵投资。让我们不断磨砺自己,与时代共同进步,书写属于我们的辉煌篇章。

需要完整版PDF学习资源私我

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以点击这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值