一、文件名路径设置
在 Windows 中,从文件目录复制出来的路径样式如下:
D:_OperateAspectJspectj-1.8.10lib
如果将上述路径用作 C 语言中的字符串,可以使用:
D:\004_Operate\AspectJ\aspectj-1.8.10\lib
或者使用:
D:/004_Operate/AspectJ/aspectj-1.8.10/lib
建议使用后者,即 D:/004_Operate/AspectJ/aspectj-1.8.10/lib,这种格式的文件路径既可以在 Windows 中使用,也可以在 Linux 中使用。
二、文件打开方式
请参考【C 语言】文件操作(fopen 文件打开方式详解)博客。
三、fputc 函数 | 按照字符方式写文件
1、fputc 函数
fputc 函数:将 int c 字符写入到 FILE *fp 文件中。
#include <stdio.h> int fputc (int c, FILE *fp)
2、代码示例
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
<p>/**</p><ul><li><p>@brief 主函数入口</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1098">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680092332148.png" alt="怪兽AI数字人">
</a>
<div class="aritcle_card_info">
<a href="/ai/1098">怪兽AI数字人</a>
<p>数字人短视频创作,数字人直播,实时驱动数字人</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="怪兽AI数字人">
<span>44</span>
</div>
</div>
<a href="/ai/1098" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="怪兽AI数字人">
</a>
</div>
</li><li><p>@return
<em>/
int main(int argc, char</em> argv[], char*<em>env)
{
// 要写出的字符串数据
char </em>str = "Hello World!";
// 文件指针
FILE <em>fp = NULL;
// 文件路径
char </em>filename = "D:/File/file.txt";
// 循环控制变量
int i = 0;</p><p>// 以 读写 方式打开 文本文件,
// 如果文件不存在创建文件,
// 如果文件存在 清空后 重新写入
fp = fopen(filename, "w+");</p><p>// 向文件中写出数据
for (i = 0; i < strlen(str); i++)
{
fputc(str[i], fp);
}</p><p>// 关闭文件
fclose(fp);</p><p>// 命令行不要退出
system("pause");</p><p>return 0;
}执行结果:

四、fgetc 函数 | 按照字符方式读文件
1、fgetc 函数
fgetc 函数:从 FILE <em>stream</em> 指针指向的文件中,读取一个字符。
#include <stdio.h> int fgetc(FILE </em>stream);
2、代码示例
代码示例:
#include <stdio.h></p><h1>include <stdlib.h></h1><h1>include <string.h></h1></li></ul><p>/**</p><ul><li><p>@brief 主函数入口</p></li><li><p>@return
<em>/
int main(int argc, char</em> argv[], char*<em>env)
{
// 文件指针
FILE </em>fp = NULL;
// 文件路径
char *filename = "D:/File/file.txt";
// 循环控制变量
int i = 0;</p><p>// 以 读写 方式打开 文本文件
// 文件必须存在,如果文件不存在则报错
fp = fopen(filename, "r+");</p><p>// 从文件中读取数据
while (!feof(fp))
{
// 读取一个字符
char c = fgetc(fp);
// 打印单个字符
printf("%c", c);
}</p><p>// 打印换行
printf("
");</p><p>// 关闭文件
fclose(fp);</p><p>// 命令行不要退出
system("pause");</p><p>return 0;
}执行结果:

以上就是【C 语言】文件操作 ( 按照单个字符的方式读写文件 | fgetc 函数 | fputc 函数 )的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号