C语言中文件操作的putc()和getc()函数详解

文件是记录的集合,或者是硬盘上的一个位置,数据永久存储在其中。

对文件的操作

C语言编程语言对文件的操作如下−

  • 命名文件
  • 打开文件
  • 从文件中读取
  • 写入文件
  • 关闭文件

语法

打开文件的语法如下

FILE *File pointer;

例如,FILE * fptr;

命名文件的语法如下

File pointer = fopen ("File name", "mode");

例如

fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w");

putc( ) 和 getc( ) 函数

putc( ) 函数用于将字符写入文件。

  • 功能putc() 函数用于将一个字符写入到指定的文件流中。
  • 语法int putc(int char, FILE *stream);
  • 参数
    • char:要写入的字符(传递给函数时会被隐式转换为 unsigned char 类型)。
    • stream:指向 FILE 对象的指针,该对象标识要写入字符的流。
  • 返回值:成功时返回写入的字符。如果发生写错误,则返回 EOF。

putc() 函数的语法如下

putc (char ch, FILE *fp);

例如

#include <stdio.h>

int main() {
    FILE *fp;
    int c;

    fp = fopen("output.txt", "w");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    for (c = 'A'; c <= 'Z'; c++) {
        putc(c, fp);
    }

    fclose(fp);
    return 0;
}

getc( ) 函数用于从文件中读取字符。

  • 功能getc() 函数用于从指定的文件流中读取一个字符。
  • 语法int getc(FILE *stream);
  • 参数stream 是指向 FILE 对象的指针,该对象标识要从中读取字符的流。
  • 返回值:成功时返回读取的字符(作为一个无符号字符转换为 int 类型)。如果遇到文件末尾或发生读错误,则返回 EOF。

getc() 函数的语法如下

char getc (FILE *fp);

例如

#include <stdio.h>

int main() {
    FILE *fp;
    int c;

    fp = fopen("output.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    while ((c = getc(fp)) != EOF) {
        putchar(c);
    }

    fclose(fp);
    return 0;
}

以下是使用 putc() 和 getc() 函数的 C 程序

#include<stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w"); //opening file in write mode
   printf("enter the text.press cntrl Z:
");
   while((ch = getchar())!=EOF){
      putc(ch,fp); // writing each character into the file
   }
   fclose(fp);
   fp=fopen("std1.txt","r");
   printf("text on the file:
");
   while ((ch=getc(fp))!=EOF){ // reading each character from file
      putchar(ch); // displaying each character on to the screen
   }
   fclose(fp);
   return 0;
}

输出

当执行上述程序时,它会产生以下结果 -

enter the text.press cntrl Z:
Hi Welcome to TutorialsPoint
Here I am Presenting Question and answers in C Programming Language
^Z
text on the file:
Hi Welcome to TutorialsPoint
Here I am Presenting Question and answers in C Programming Language

总结

  • putc() 用于将一个字符写入到文件中,返回该字符或 EOF。
  • getc() 用于从文件中读取一个字符,返回该字符或 EOF。
  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新华

感谢打赏,我会继续努力原创。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值