南通网站设计制作,门户型网站模板,wordpress 手机pc,太原网站seo顾问文章目录 1. fopen函数2. fclose函数3. fgetc函数4. fgets函数5. fputc函数6. fputs函数7. fprintf函数8. fscanf函数9. fseek函数10. ftell函数 1. fopen函数
返回值#xff1a;文件指针#xff08;FILE*#xff09;参数#xff1a;文件名#xff08;包括文件路径#… 文章目录 1. fopen函数2. fclose函数3. fgetc函数4. fgets函数5. fputc函数6. fputs函数7. fprintf函数8. fscanf函数9. fseek函数10. ftell函数 1. fopen函数
返回值文件指针FILE*参数文件名包括文件路径、打开模式例如r表示只读w表示写入a表示追加用法用于打开一个文件并返回一个文件指针以便后续的文件操作。
#include stdio.hint main() {FILE *file fopen(example.txt, r);if (file NULL) {printf(Failed to open the file.\n);return 1;}// 文件操作...fclose(file);return 0;
}2. fclose函数
返回值整数类型0表示成功EOF表示失败参数文件指针FILE*用法用于关闭一个已打开的文件。
#include stdio.hint main() {FILE *file fopen(example.txt, r);if (file NULL) {printf(Failed to open the file.\n);return 1;}// 文件操作...fclose(file);return 0;
}3. fgetc函数
返回值整数类型读取的字符的ASCII码值读取失败返回EOF参数文件指针FILE*用法用于从文件中读取一个字符。
#include stdio.hint main() {FILE *file fopen(example.txt, r);if (file NULL) {printf(Failed to open the file.\n);return 1;}int ch;while ((ch fgetc(file)) ! EOF) {printf(%c, ch);}fclose(file);return 0;
}4. fgets函数
返回值字符指针读取的字符串读取失败返回NULL参数字符数组、最大读取字符数、文件指针FILE*用法用于从文件中读取一行字符串。
#include stdio.hint main() {FILE *file fopen(example.txt, r);if (file NULL) {printf(Failed to open the file.\n);return 1;}char buffer[100];while (fgets(buffer, 100, file) ! NULL) {printf(%s, buffer);}fclose(file);return 0;
}5. fputc函数
返回值整数类型写入的字符的ASCII码值写入失败返回EOF参数字符、文件指针FILE*用法用于向文件中写入一个字符。
#include stdio.hint main() {FILE *file fopen(example.txt, w);if (file NULL) {printf(Failed to open the file.\n);return 1;}char ch A;fputc(ch, file);fclose(file);return 0;
}6. fputs函数
返回值整数类型成功返回非负值失败返回EOF参数字符串、文件指针FILE*用法用于向文件中写入一个字符串。
#include stdio.hint main() {FILE *file fopen(example.txt, w);if (file NULL) {printf(Failed to open the file.\n);return 1;}char *str Hello, World!;fputs(str, file);fclose(file);return 0;
}7. fprintf函数
返回值整数类型成功返回写入的字符数失败返回负值参数文件指针FILE*、格式化字符串、可变参数用法用于按照指定的格式将数据写入文件。
#include stdio.hint main() {FILE *file fopen(example.txt, w);if (file NULL) {printf(Failed to open the file.\n);return 1;}int num 10;fprintf(file, The number is: %d\n, num);fclose(file);return 0;
}8. fscanf函数
返回值整数类型成功返回读取的项目数失败返回负值参数文件指针FILE*、格式化字符串、可变参数用法用于从文件中按照指定的格式读取数据。
#include stdio.hint main() {FILE *file fopen(example.txt, r);if (file NULL) {printf(Failed to open the file.\n);return 1;}int num;fscanf(file, %d, num);printf(The number is: %d\n, num);fclose(file);return 0;
}9. fseek函数
返回值整数类型0表示成功非0表示失败参数文件指针FILE*、偏移量long int、起始位置int用法用于设置文件指针的位置实现文件的定位操作。
10. ftell函数
返回值长整型当前文件指针的位置参数文件指针FILE*用法用于获取文件指针的当前位置。
下面是fseek和ftell函数的示例代码
#include stdio.hint main() {FILE *file fopen(example.txt, r);if (file NULL) {printf(Failed to open the file.\n);return 1;}// 使用fseek函数定位文件指针到文件末尾fseek(file, 0, SEEK_END);// 使用ftell函数获取文件指针的当前位置long int size ftell(file);printf(The size of the file is: %ld bytes\n, size);fclose(file);return 0;
}在上述示例代码中首先打开了一个文件然后使用fseek函数将文件指针定位到文件末尾接着使用ftell函数获取文件指针的当前位置即文件的大小。最后关闭文件。
使用fseek函数和ftell函数可以实现文件的定位和随机读写操作。