免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 558 | 回复: 0
打印 上一主题 下一主题

文件和目录(file and catalog) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-10 16:07 |只看该作者 |倒序浏览

               
               
                文件和目录
fopen, fclose, fread, fwrite, fgetc, fgets, fseek, fflush, remove, rename
reference site http://linux.die.net
Name
fopen, fdopen, freopen - stream open functions
Synopsis
#include stdio.h>
FILE *fopen(const char *path, const char *mode);
FILE *fdopen(int fd, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);
Description
The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it.
The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):
r
    Open text file for reading. The stream is positioned at the beginning of the file.
r+
    Open for reading and writing. The stream is positioned at the beginning of the file.
w
    Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
w+
    Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
a
    Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
a+
    Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
The mode string can also include the letter ''b'' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the ''b'' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the ''b'' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)
Any created files will have mode S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH (0666), as modified by the process' umask value (see umask(2)).
Reads and writes may be intermixed on read/write streams in any order. Note that ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file. (If this condition is not met, then a read is allowed to return the result of writes other than the most recent.) Therefore it is good practice (and indeed sometimes necessary under Linux) to put an fseek() or fgetpos() operation between write and read operations on such a stream. This operation may be an apparent no-op (as in fseek(..., 0L, SEEK_CUR) called for its synchronizing side effect.
Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded by an
    fseek(stream,0,SEEK_END);
call.
The fdopen() function associates a stream with the existing file descriptor, fildes. The mode of the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be compatible with the mode of the file descriptor. The file position indicator of the new stream is set to that belonging to fildes, and the error and end-of-file indicators are cleared. Modes "w" or "w+" do not cause truncation of the file. The file descriptor is not dup'ed, and will be closed when the stream created by fdopen() is closed. The result of applying fdopen() to a shared memory object is undefined.
The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the fopen() function. The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout).
Return Value
Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.
Name
clearerr, feof, ferror, fileno - check and reset stream status
Synopsis
#include stdio.h>
void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
int fileno(FILE *stream);
Description
The function clearerr() clears the end-of-file and error indicators for the stream pointed to by stream.
The function feof() tests the end-of-file indicator for the stream pointed to by stream, returning non-zero if it is set. The end-of-file indicator can only be cleared by the function clearerr().
The function ferror() tests the error indicator for the stream pointed to by stream, returning non-zero if it is set. The error indicator can only be reset by the clearerr() function.
The function fileno() examines the argument stream and returns its integer descriptor.
For non-locking counterparts, see unlocked_stdio(3).
example:
  while(!feof(stream))
  {
  //do stuff
}
or int c;
while(c=fgetc(stream)!=EOF)
{
//do stuff
}
注意:fgetc返回的是整数,调用clearerr可以清除流的EOF标志和出错标志
Name
fgetc, fgets, getc, getchar, gets, ungetc - input of characters and strings
Synopsis
#include stdio.h>
int fgetc(FILE *stream);
char *fgets(char *s, int size, FILE *stream);
int getc(FILE *stream);
int getchar(void);
char *gets(char *s);
int ungetc(int c, FILE *stream);
Description
fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.
getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.
getchar() is equivalent to getc(stdin).
gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with '\0'. No check for buffer overrun is performed (see BUGS below).
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.
ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.
Calls to the functions described here can be mixed with each other and with calls to other input functions from the stdio library for the same input stream.
For non-locking counterparts, see unlocked_stdio(3).
Return Value
fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.
gets() and fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read.
ungetc() returns c on success, or EOF on error.
Name
fgetpos, fseek, fsetpos, ftell, rewind - reposition a stream
Synopsis
#include stdio.h>
int fseek(FILE *stream, long offset, int whence);
long ftell(FILE *stream);
void rewind(FILE *stream);
int fgetpos(FILE *stream, fpos_t *pos);
int fsetpos(FILE *stream, fpos_t *pos);
Description
The fseek() function sets the file position indicator for the stream pointed to by stream. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the current position indicator, or end-of-file, respectively. A successful call to the fseek() function clears the end-of-file indicator for the stream and undoes any effects of the ungetc(3) function on the same stream.
The ftell() function obtains the current value of the file position indicator for the stream pointed to by stream.
The rewind() function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to:
    (void)fseek(stream, 0L, SEEK_SET)
except that the error indicator for the stream is also cleared (see clearerr(3)).
The fgetpos() and fsetpos() functions are alternate interfaces equivalent to ftell() and fseek() (with whence set to SEEK_SET), setting and storing the current value of the file offset into or from the object referenced by pos. On some non-UNIX systems an fpos_t object may be a complex object and these routines may be the only way to portably reposition a text stream.
Return Value
The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() return 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error.
删除和改名
Name
rename - change the name or location of a file
Synopsis
#include stdio.h>
int rename(const char *oldpath, const char *newpath);
Description
rename() renames a file, moving it between directories if required.
Any other hard links to the file (as created using link(2)) are unaffected.
If newpath already exists it will be atomically replaced (subject to a few conditions; see ERRORS below), so that there is no point at which another process attempting to access newpath will find it missing.
If newpath exists but the operation fails for some reason rename() guarantees to leave an instance of newpath in place.
However, when overwriting there will probably be a window in which both oldpath and newpath refer to the file being renamed.
If oldpath refers to a symbolic link the link is renamed; if newpath refers to a symbolic link the link will be overwritten.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
Name
remove - delete a name and possibly the file it refers to
Synopsis
#include stdio.h>
int remove(const char *pathname);
Description
remove() deletes a name from the filesystem. It calls unlink() for files, and rmdir() for directories.
If the removed name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.
If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.
If the name referred to a symbolic link the link is removed.
If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
Name
fflush - flush a stream
Synopsis
#include stdio.h>
int fflush(FILE *stream);
Description
The function fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. The open status of the stream is unaffected.
If the stream argument is NULL, fflush() flushes all open output streams.
For a non-locking counterpart, see unlocked_stdio(3).
Return Value
Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error.
目录:
Name
getcwd       get_current_dir_name, 找到当前目录名
getwd - Get current working directory
Synopsis
#include
char *getcwd(char *buf, size_t size);char *get_current_dir_name(void);char
*getwd(char *buf);
Description
The getcwd() function copies an absolute pathname of the current working directory to the array pointed to by buf, which is of length size.
If the current absolute pathname would require a buffer longer than size elements, NULL is returned, and errno is set to ERANGE; an application should check for this error, and allocate a larger buffer if necessary.
If buf is NULL, the behaviour of getcwd() is undefined.
As an extension to the POSIX.1-2001 standard, Linux (libc4, libc5, glibc) getcwd() allocates the buffer dynamically using malloc() if buf is NULL on call. In this case, the allocated buffer has the length size unless size is zero, when buf is allocated as big as necessary. It is possible (and, indeed, advisable) to free() the buffers if they have been obtained this way.
get_current_dir_name(), which is only prototyped if _GNU_SOURCE is defined, will malloc(3) an array big enough to hold the current directory name. If the environment variable PWD is set, and its value is correct, then that value will be returned.
getwd(), which is only prototyped if _BSD_SOURCE or _XOPEN_SOURCE_EXTENDED is defined, will not malloc(3) any memory. The buf argument should be a pointer to an array at least PATH_MAX bytes long. getwd() does only return the first PATH_MAX bytes of the actual pathname. Note that PATH_MAX need not be a compile-time constant; it may depend on the filesystem and may even be unlimited. For portability and security reasons, use of getwd() is deprecated.
Return Value
NULL on failure with errno set accordingly, and buf on success. The contents of the array pointed to by buf is undefined on error.
改变目录
Name
chdir, fchdir - change working directory
Synopsis
#include
int chdir(const char *path);
int fchdir(int fd);
Description
chdir() changes the current working directory to that specified in path.
fchdir() is identical to chdir(); the only difference is that the directory is given as an open file descriptor.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
创建目录
Name
mkdir - create a directory
Synopsis
#include #include
int mkdir(const char *pathname, mode_t mode);
Description
mkdir() attempts to create a directory named pathname.
The parameter mode specifies the permissions to use. It is modified by the process's umask in the usual way: the permissions of the created directory are (mode & ~umask & 0777). Other mode bits of the created directory depend on the operating system. For Linux, see below.
The newly created directory will be owned by the effective user ID of the process. If the directory containing the file has the set-group-ID bit set, or if the filesystem is mounted with BSD group semantics, the new directory will inherit the group ownership from its parent; otherwise it will be owned by the effective group ID of the process.
If the parent directory has the set-group-ID bit set then so will the newly created directory.
Return Value
mkdir() returns zero on success, or -1 if an error occurred (in which case, errno is set appropriately).
删除目录
Name
rmdir - remove a directory
Synopsis
#include unistd.h>
int rmdir(const char *path);
Description
The rmdir() function shall remove a directory whose name is given by path. The directory shall be removed only if it is an empty directory.
If the directory is the root directory or the current working directory of any process, it is unspecified whether the function succeeds, or whether it shall fail and set errno to [EBUSY].
If path names a symbolic link, then rmdir() shall fail and set errno to [ENOTDIR].
If the path argument refers to a path whose final component is either dot or dot-dot, rmdir() shall fail.
If the directory
's link count becomes 0 and no process has the directory open, the space occupied by the directory shall be freed and the directory shall no longer be accessible. If one or more processes have the directory open when the last link is removed, the dot and dot-dot entries, if present, shall be removed before rmdir() returns and no new entries may be created in the directory, but the directory shall not be removed until all references to the directory are closed.
If the directory is not an empty directory, rmdir() shall fail and set errno to [EEXIST] or [ENOTEMPTY].
Upon successful completion, the rmdir() function shall mark for update the st_ctime and st_mtime fields of the parent directory.
Return Value
Upon successful completion, the function rmdir() shall return 0. Otherwise, -1 shall be returned, and errno set to indicate the error. If -1 is returned, the named directory shall not be changed.
获取目录列表:
1.使用opendir函数打开目录文件
2.使用readdir函数读出目录文件的内容
3,使用closedir函数关闭目录文件
opendir - open a directory
Synopsis
#include
#include
DIR *opendir(const char *name);
Description
The opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the directory stream. The stream is positioned at the first entry in the directory.
Return Value
The opendir() function returns a pointer to the directory stream. On error, NULL is returned, and errno is set appropriately.
Name
readdir - read a directory
Synopsis
#include
#include
struct dirent *readdir(DIR *dir);
Description
The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dir. It returns NULL on reaching the end-of-file or if an error occurred.
On Linux, the dirent structure is defined as follows:
    struct dirent {
        ino_t          d_ino;       /* inode number */
        off_t          d_off;       /* offset to the next dirent */
        unsigned short d_reclen;    /* length of this record */
        unsigned char  d_type;      /* type of file */
        char           d_name[256]; /* filename */
    };
According to POSIX, the dirent structure contains a field char d_name[] of unspecified size, with at most NAME_MAX characters preceding the terminating null byte. POSIX.1-2001 also documents the field ino_t d_ino as an XSI extension. Use of other fields will harm the portability of your programs.
The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.
Return Value
The readdir() function returns a pointer to a dirent structure, or NULL if an error occurs or end-of-file is reached. On error, errno is set appropriately.
Name
closedir - close a directory
Synopsis
#include
#include
int closedir(DIR *dir);
Description
The closedir() function closes the directory stream associated with dir. The directory stream descriptor dir is not available after this call.
Return Value
The closedir() function returns 0 on success. On error, -1 is returned, and errno is set appropriately.
******example*************8
#include
#include   //assert(expression) need
int main( void )
{
       FILE *fp;
   
       fp = fopen( "test.txt", "w" );//以可写的方式打开一个文件,如果不存在就创建一个同名文件
       assert( fp );                          //所以这里不会出错  assert() 里的参数也可以是表达式
       fclose( fp );
   
       fp = fopen( "noexitfile.txt", "r" );//以只读的方式打开一个文件,如果不存在就打开文件失败
       assert( fp );                           //所以这里出错
       fclose( fp );                           //程序永远都执行不到这里来
       return 0;
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/45689/showart_683510.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP