C-文件处理-读写字符
时间:2020-02-23 14:31:54 来源:igfitidea点击:
在本教程中,我们将学习使用C编程语言在文件中读写字符。
在上一教程中,我们已经学习了如何在C中创建文件。
随时检查一下。
getc和putc I/O函数
我们使用getc()和putc()I/O函数分别从文件中读取字符并将字符写入文件。
getc的语法:
char ch = getc(fptr);
其中," fptr"是文件指针。
注意! EOF标记文件结束。
当我们遇到EOF字符时,表示我们已经到达文件末尾。
putc的语法:
putc(ch, fptr);
其中," ch"是要写入的字符," fptr"是文件指针。
用C编写程序以创建一个新文件并保存用户名作为用户输入
为此,我们将首先创建一个" FILE"指针,并创建一个名为" username.txt"的文件。
随意使用您喜欢的任何其他文件名。
然后,我们将使用putc()函数将字符写入文件中。
一旦完成,我们就可以使用getc()函数读取文件数据,直到我们点击EOF并将其显示在控制台中为止。
完整的代码:
#include <stdio.h>
int main(void) {
//creating a FILE variable
FILE *fptr;
//creating a character variable
char ch;
//open the file in write mode
fptr = fopen("username.txt", "w");
//take user input
printf("Enter your name: ");
//keep reading the user input from the terminal
//till Return (Enter) key is pressed
while( (ch = getchar()) != '\n' ) {
//write character ch in file
putc(ch, fptr);
}
//close the file
fclose(fptr);
//open the file in read mode
fopen("username.txt", "r");
//display the content of the file
printf("\nFile content:\n");
while( (ch = getc(fptr)) != EOF ) {
printf("%c", ch);
}
printf("\nEnd of file\n");
//close file
fclose(fptr);
return 0;
}
Enter your name: File content: End of file

