首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于资料的读写操作

2013-10-04 
关于文件的读写操作大家好,本人的问题是:由于本人需要写多个.cpp文件,其中每个.cpp文件中都需要向同一个文

关于文件的读写操作
大家好,本人的问题是:
  
     由于本人需要写多个.cpp文件,其中每个.cpp文件中都需要向同一个文件写数据,所以我采用fopen函数
打开文件,fwrite函数写数据。问题是,比如1.cpp中写了数据到文件file.txt,然后fclose关闭。当2.cpp文件
向file.txt文件写数据时,只能是按照fopen函数的"ab"或"wb"的方式,要么是在最后位置写,要么是将原来的数据清零后重新写,而不能用fseek函数定位到指定位置写入数据。 本人猜想是由于fclose释放了所有文件资源的缘故,但是如果我要实现文件定位怎么办,难道是打开文件后就一直不关闭? 求赐教,谢谢~~ 数据 c/c++ 文件操作
[解决办法]
二进制方式读写文件操作而已!
每次打开文件关闭文件后,再打开的话,文件读指针就在文件开头了!所以覆盖是正常的!
所以第二次打开文件的时候可以用fseek来偏移指针的!或者可以打开写操作后,不立即关闭文件,继续写操作最好,最后写完再关闭,节约系统调用的消耗
[解决办法]
判断下你打开的返回值吧!估计你都没有成功打开文件呢!

注意windows下""是个逃逸字符,

路径用"\";
[解决办法]
_locking
Locks or unlocks bytes of a file.

int _locking( int handle, int mode, long nbytes );

Routine Required Header Optional Headers Compatibility 
_locking <io.h> and <sys/locking.h> <errno.h> Win 95, Win NT 


For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version 
LIBCMT.LIB Multithread static library, retail version 
MSVCRT.LIB Import library for MSVCRT.DLL, retail version 


Return Value

_locking returns 0 if successful. A return value of –1 indicates failure, in which case errno is set to one of the following values:

EACCES

Locking violation (file already locked or unlocked).

EBADF

Invalid file handle.

EDEADLOCK

Locking violation. Returned when the _LK_LOCK or _LK_RLCK flag is specified and the file cannot be locked after 10 attempts.

EINVAL

An invalid argument was given to _locking.

Parameters

handle

File handle

mode

Locking action to perform

nbytes

Number of bytes to lock

Remarks

The _locking function locks or unlocks nbytes bytes of the file specified by handle. Locking bytes in a file prevents access to those bytes by other processes. All locking or unlocking begins at the current position of the file pointer and proceeds for the next nbytes bytes. It is possible to lock bytes past end of file.

mode must be one of the following manifest constants, which are defined in LOCKING.H:

_LK_LOCK

Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked, the constant returns an error.

_LK_NBLCK

Locks the specified bytes. If the bytes cannot be locked, the constant returns an error.

_LK_NBRLCK

Same as _LK_NBLCK.

_LK_RLCK

Same as _LK_LOCK.

_LK_UNLCK

Unlocks the specified bytes, which must have been previously locked.

Multiple regions of a file that do not overlap can be locked. A region being unlocked must have been previously locked. _locking does not merge adjacent regions; if two locked regions are adjacent, each region must be unlocked separately. Regions should be locked only briefly and should be unlocked before closing a file or exiting the program.

Example

/* LOCKING.C: This program opens a file with sharing. It locks
 * some bytes before reading them, then unlocks them. Note that the
 * program works correctly only if the file exists.
 */

#include <io.h>
#include <sys/types.h>


#include <sys/stat.h>
#include <sys/locking.h>
#include <share.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

void main( void )
{
   int  fh, numread;
   char buffer[40];

   /* Quit if can't open file or system doesn't 
    * support sharing. 
    */
   fh = _sopen( "locking.c", _O_RDWR, _SH_DENYNO, 
                 _S_IREAD 
[解决办法]
 _S_IWRITE );
   if( fh == -1 )
      exit( 1 );

   /* Lock some bytes and read them. Then unlock. */
   if( _locking( fh, LK_NBLCK, 30L ) != -1 )
   {
      printf( "No one can change these bytes while I'm reading them\n" );
      numread = _read( fh, buffer, 30 );
      printf( "%d bytes read: %.30s\n", numread, buffer );
      lseek( fh, 0L, SEEK_SET );
     _locking( fh, LK_UNLCK, 30L );
      printf( "Now I'm done. Do what you will with them\n" );
   }
   else
      perror( "Locking failed\n" );

   _close( fh );
}


Output

No one can change these bytes while I'm reading them
30 bytes read: /* LOCKING.C: This program ope
Now I'm done. Do what you will with them


File Handling Routines

See Also   _creat, _open

[解决办法]
不释放文件会被锁住的,可以用个变量标记下偏移量
[解决办法]
_fsopen, _wfsopen
Open a stream with file sharing.

FILE *_fsopen( const char *filename, const char *mode, int shflag );

FILE *_wfsopen( const wchar_t *filename, const wchar_t *mode, int shflag );

Function Required Header Optional Headers Compatibility 
_fsopen <stdio.h> <share.h>1 Win 95, Win NT 
_wfsopen <stdio.h> or <wchar.h> <share.h>1 Win NT 


1 For manifest constant for shflag parameter.

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version 
LIBCMT.LIB Multithread static library, retail version 
MSVCRT.LIB Import library for MSVCRT.DLL, retail version 


Return Value

Each of these functions returns a pointer to the stream. A NULL pointer value indicates an error.

Parameters

filename

Name of file to open

mode

Type of access permitted

shflag

Type of sharing allowed

Remarks

The _fsopen function opens the file specified by filename as a stream and prepares the file for subsequent shared reading or writing, as defined by the mode and shflag arguments. _wfsopen is a wide-character version of _fsopen; the filename and mode arguments to _wfsopen are wide-character strings. _wfsopen and _fsopen behave identically otherwise.

Generic-Text Routine Mappings

TCHAR.H Routine  _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined 
_tfsopen _fsopen _fsopen _wfsopen 


The character string mode specifies the type of access requested for the file, as follows:

"r"

Opens for reading. If the file does not exist or cannot be found, the _fsopen call fails.

"w"

Opens an empty file for writing. If the given file exists, its contents are destroyed.

"a"

Opens for writing at the end of the file (appending); creates the file first if it does not exist.



"r+"

Opens for both reading and writing. (The file must exist.)

"w+"

Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.

"a+"

Opens for reading and appending; creates the file first if it does not exist.

Use the "w" and "w+" types with care, as they can destroy existing files.

When a file is opened with the "a" or "a+" access type, all write operations occur at the end of the file. The file pointer can be repositioned using fseek or rewind, but is always moved back to the end of the file before any write operation is carried out. Thus existing data cannot be overwritten. When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for “update”). However, when switching between reading and writing, there must be an intervening fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired. In addition to the above values, one of the following characters can be included in mode to specify the translation mode for new lines:

t

Opens a file in text (translated) mode. In this mode, carriage return–linefeed (CR-LF) combinations are translated into single linefeeds (LF) on input and LF characters are translated to CR-LF combinations on output. Also, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading or reading/writing, _fsopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using fseek and ftell to move within a file that ends with a CTRL+Z may cause fseek to behave improperly near the end of the file.

b

Opens a file in binary (untranslated) mode; the above translations are suppressed.

If t or b is not given in mode, the translation mode is defined by the default-mode variable _fmode. If t or b is prefixed to the argument, the function fails and returns NULL. For a discussion of text and binary modes, see Text and Binary Mode File I/O. 

The argument shflag is a constant expression consisting of one of the following manifest constants, defined in SHARE.H:

_SH_COMPAT

Sets Compatibility mode for 16-bit applications

_SH_DENYNO

Permits read and write access

_SH_DENYRD

Denies read access to file

_SH_DENYRW

Denies read and write access to file

_SH_DENYWR

Denies write access to file

Example

/* FSOPEN.C:
 */

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

void main( void )
{
   FILE *stream;

   /* Open output file for writing. Using _fsopen allows us to
    * ensure that no one else writes to the file while we are
    * writing to it.
    */
   if( (stream = _fsopen( "outfile", "wt", _SH_DENYWR )) != NULL )
   {
      fprintf( stream, "No one else in the network can write "
                       "to this file until we are done.\n" );
      fclose( stream );
   }
   /* Now others can write to the file while we read it. */
   system( "type outfile" );
}


Output

No one else in the network can write to this file until we are done.




Stream I/O Routines

See Also   fclose, _fdopen, ferror, _fileno, fopen, freopen, _open, _setmode, _sopen

热点排行