关于fdopen的段错误问题,求助

bw_0927 2010-07-27 11:10:36

#include <stdio.h>
#include <stdlib.h>

int main()
{
char ch[20];
FILE *fp = fdopen("./tmp", "r+);
fscanf(fp, "%s" , ch);
printf("%s\n", ch);
return 0;
}

仔细看了下man,好像fdopen的第一个参数是需要一个文件描述符,因此改成了下面的版本
int main()
{
char ch[20];
int fd = open("./tmp", O_RDWR);
FILE *fp = fdopen(fd, "r+);
fscanf(fp, "%s" , ch);
printf("%s\n", ch);
return 0;
}


tmp的文件内容是:
this is a test
this is a test
this is a test


是哪里出错了?谢谢
...全文
124 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangweiit 2010-07-28
  • 打赏
  • 举报
回复
段错误的话,那明显是内存问题了

你把char[20]再放大一点看一下
换成char ch[100];试试看
SLSnake 2010-07-27
  • 打赏
  • 举报
回复
建议楼主检查下
int fd = open("./tmp", O_RDWR);
这句成功运行没有
怀疑路径是不是给错了
SLSnake 2010-07-27
  • 打赏
  • 举报
回复

int main()
{
char ch[20];
int fd = _open("tmp", O_RDWR);
FILE *fp = _fdopen(fd, "r+");
fscanf(fp, "%s" , ch);
printf("%s\n", ch);
return 0;
}

VC6中成功运行,不知道楼主的问题解决没有
bw_0927 2010-07-27
  • 打赏
  • 举报
回复
是疏忽写错了,源文件中就是这样的“FILE *fp = fdopen(fd, "r+");”
SLSnake 2010-07-27
  • 打赏
  • 举报
回复
FILE *fp = fdopen(fd, "r+");
应该这样
SLSnake 2010-07-27
  • 打赏
  • 举报
回复

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <share.h>

int main( void )
{
FILE *stream;
int fd, count = 0;
char inbuf[128];

// Open a file.
if( _sopen_s( &fd, "crt_fdopen.txt", _O_RDONLY, _SH_DENYNO, 0 ) )
exit( 1 );

// Get stream from file descriptor.
if( (stream = _fdopen( fd, "r" )) == NULL )
exit( 1 );

while( fgets( inbuf, 128, stream ) != NULL )
count++;

// After _fdopen, close with fclose, not _close.
fclose( stream );
printf( "Lines in file: %d\n", count );
}

MSDN 上的例子,希望有帮助
肥多罗 2010-07-27
  • 打赏
  • 举报
回复
看看tmp这个文件本身的权限,要不chmod 777 tmp 试试
ilwmin 2010-07-27
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 bw_0927 的回复:]
没有错哦,你说的地方都是对的
[/Quote]
int fd = open("./tmp", O_RDWR);
我这里没问题.看一下这句的返回值是多少?如果是-1就肯定是路径不对.
赵4老师 2010-07-27
  • 打赏
  • 举报
回复
TCHAR.H Routine  _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined 
_tfdopen _fdopen _fdopen _wfdopen

/* _FDOPEN.C: This program opens a file using low-
* level I/O, then uses _fdopen to switch to stream
* access. It counts the lines in the file.
*/

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

void main( void )
{
FILE *stream;
int fh, count = 0;
char inbuf[128];

/* Open a file handle. */
if( (fh = _open( "_fdopen.c", _O_RDONLY )) == -1 )
exit( 1 );

/* Change handle access to stream access. */
if( (stream = _fdopen( fh, "r" )) == NULL )
exit( 1 );

while( fgets( inbuf, 128, stream ) != NULL )
count++;

/* After _fdopen, close with fclose, not _close. */
fclose( stream );
printf( "Lines in file: %d\n", count );
}


bw_0927 2010-07-27
  • 打赏
  • 举报
回复
没有错哦,你说的地方都是对的

69,377

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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