69,377
社区成员
发帖
与我相关
我的任务
分享
#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
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;
}
#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 );
}
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 );
}