c - fopen 给我一个分段错误
问题描述
我正在尝试打开 output_voice_capture.txt 但它给了我一个分段错误,不仅文件存在而且它具有读取权限。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fPtr;
char ch;
/*
* Open file in r (read) mode.
*/
printf("Opening file ......\n");
fPtr = fopen("/flash/etc/output_voice_capture.txt", "r");
if(fPtr == NULL)
{
/* Unable to open file hence exit */
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/* File open success message */
printf("File opened successfully. Reading file contents character by character.\n");
do
{ printf("Read single character from file ......\n");
/* Read single character from file */
ch = fgetc(fPtr);
/* Print character read code ASCII on console */
printf ("%d \n", ch);
} while(ch != EOF); /* Repeat this if last read character is not EOF */
printf("Closing file ......\n");
fclose(fPtr);
return 0;
}
我正在使用包含所有我可以使用的 bin 的 minicom,问题是当我使用 linux 终端和一个简单的 .txt 测试文件时,代码工作得很好。
解决方案
- 正如Zaboj Campula在他的评论中已经说过的那样,EOF 被定义为 -1 的整数。在某些系统上,char 是 0..255 的值,在其他系统上是 -127..128 的值。为避免任何问题,应使用
feof()
函数(链接)检查流的结尾。由于 char 和 int 的大小不同,这可能是您的问题的根源。 - 您的代码将打印“文件已成功打开。逐字符读取文件内容。” 对于每个读取的字符。
- 只在一个地方保留功能:最后。这使您的代码更具可读性
- 当你的部分代码依赖于某些东西时,用错误检查将它括起来。
试试这个代码:
int main() {
FILE * fPtr;
char ch;
int result = 0;
printf("Opening file ......\n");
if (!(fPtr = fopen("/flash/etc/output_voice_capture.txt", "r")) {
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
result = EXIT_FAILURE;
} else {
printf("File opened successfully. Reading file contents character by character.\n");
while (EOF != (ch = fgetc(fPtr))) {
printf ("%d \n", ch);
}
fclose(fPtr);
}
return result;
}
推荐阅读
- postgresql - 如何从合并中删除重复项
- ios - 我试图在我的 ViewController 上放置多个 UICollectionView,但模拟中只有一个 UICollectionView 正在运行
- python - 在云函数中执行 python flask-assistant 代码时遇到问题
- html-to-pdf - SelectPDF不打印背景svg图像
- python - 如何让测验显示学生答案并显示正确答案和成绩?
- javascript - 在 javascript 中从 json 访问嵌套数组键、值
- r - 如何在一张纸上绘制多个图形
- r - 如何从以第一列作为参考的数据框制作列表?
- c# - 从 Web 服务生成的 html 在代码中添加反斜杠
- javascript - Discord.js 机器人记录已删除的消息不是一次而是很多