文件是记录的集合,或者是硬盘上的一个位置,数据永久存储在其中。
对文件的操作
C语言编程语言对文件的操作如下
- 命名文件
- 打开文件
- 从文件中读取
- 写入文件
- 关闭文件
语法
打开文件的语法如下
FILE *File pointer;
例如,FILE * fptr;
命名文件的语法如下 −
File pointer = fopen ("File name", "mode");
例如
fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w");
putw() 和 getw() 函数
putw() 函数用于将数字写入文件。
- 功能:
putw()
函数将一个整数写入到指定的文件流中。- 语法:
int putw(int w, FILE *stream);
- 参数:
w
是要写入的整数。stream
是指向 FILE 对象的指针,该对象标识要写入整数的流。- 返回值:成功时返回写入的整数。如果发生写错误,则返回 EOF。
putw() 函数的语法如下
语法
putw (int num, FILE *fp);
例如
#include <stdio.h>
int main() {
FILE *fp;
int i;
fp = fopen("numbers.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return -1;
}
for (i = 0; i <= 100; i += 10) {
putw(i, fp);
}
fclose(fp);
return 0;
}
getw( ) 函数用于从文件中读取数字。
- 功能:
getw()
函数从指定的文件流中读取一个整数。 - 语法:
int getw(FILE *stream);
- 参数:
stream
是指向 FILE 对象的指针,该对象标识要从中读取整数的流。 - 返回值:成功时返回读取的整数。如果遇到文件末尾或发生读错误,则返回 EOF。
getw() 函数的语法如下
语法
int getw (FILE *fp);
例如
#include <stdio.h>
int main() {
FILE *fp;
int n;
fp = fopen("numbers.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return -1;
}
while ((n = getw(fp)) != EOF) {
printf("%d ", n);
}
fclose(fp);
return 0;
}
将数字写入文件的逻辑如下
fp = fopen ("num.txt", "w");
for (i =1; i<= 10; i++){
putw (i, fp);
}
fclose (fp);
从文件中读取数字的逻辑如下
fp =fopen ("num.txt", "r");
printf ("file content is
");
for (i =1; i<= 10; i++){
i= getw(fp);
printf ("%d",i);
printf("
");
}
fclose (fp);
C 程序来演示 putw() 和 getw() 的示例
以下是用于存储从 1 到 10 的数字并打印相同的 C 程序
#include <stdio.h>
int main() {
FILE *fp;
int i;
fp = fopen("num.txt", "w");
for (i = 1; i <= 10; i++) {
putw(i, fp);
}
fclose(fp);
fp = fopen("num.txt", "r");
printf("file content is");
for (i = 1; i <= 10; i++) {
i = getw(fp);
printf("%d", i);
printf("");
}
fclose(fp);
return 0;
}
输出
当执行上述程序时,它会产生以下结果
file content is
1
2
3
4
5
6
7
8
9
10