为什么代码包含着fread就出错?

zansan 2007-11-12 10:06:13
#include <stdio.h>

main(int argc,char *argv[])
{
char a[5];
int ind;
FILE *infile=fopen("C:\1.txt", "r" );
ind=fread(a,1,6,infile);
printf("%d %d",a[0],ind);
int fc=fclose(infile);
return 0;
}

上述代码包含fread.可以通过编译,但运行就会出错,没输出.不知道是什么原因?难道我的机器有问题?
...全文
69 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zansan 2007-11-13
  • 打赏
  • 举报
回复
FILE *infile=fopen( "C:\1.txt ", "r " );
改为 FILE *infile=fopen( "1.txt ", "r " );
问题消失.估计我这机器上的C++不认绝对路径.
Iluly 2007-11-12
  • 打赏
  • 举报
回复
典型的内存段错误:

fread(a,5,1,infile);
或者
fread(a,1,5,infile);
ryfdizuo 2007-11-12
  • 打赏
  • 举报
回复
属于数组越界的问题;:
size_t fread(
void *buffer,
size_t size,
size_t count,
FILE *stream
);
Parameters
buffer
Storage location for data.
size
Item size in bytes.
count
Maximum number of items to be read.
stream
Pointer to FILE structure.
Return Value
fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. Use the feof or ferror function to distinguish a read error from an end-of-file condition. If size or count is 0, fread returns 0 and the buffer contents are unchanged.

Remarks
The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage return–linefeed pairs are replaced with single linefeed characters. The replacement has no effect on the file pointer or the return value. The file-pointer position is indeterminate if an error occurs. The value of a partially read item cannot be determined.
ryfdizuo 2007-11-12
  • 打赏
  • 举报
回复
ind=fread(a,1,6,infile);
这句有问题吧, 数组a最大容量为5;
改为:ind=fread(a,1,5,infile);
weiym 2007-11-12
  • 打赏
  • 举报
回复
C:\\1.txt
starwalker 2007-11-12
  • 打赏
  • 举报
回复
使用fopen之后应该检查infile是否为NULL
如果为NULL,就不能fread
starwalker 2007-11-12
  • 打赏
  • 举报
回复
是不是C:\1.txt不存在或者没内容?

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧