c言語のいくつかのファイル操作関数について

7310 ワード

fopen(char* filename,char* mode);ファイルを開くには、「w」または「r」のいずれかを指定します.
     fwrite(const void* buffer, size_t size, size_t count, FILE* stream )
指定したファイルにデータを書き込む
fread(void*buffer,size_t size,size_t count,FILE*stream)は、指定したファイルにデータを読み込むために使用されます.
fseek(file*stream,long offset,int origin)は、ファイルポインタの位置決めに使用され、以下の値を選択できます.
SEEK_CUR
Current position of file pointer
SEEK_END
End of file
SEEK_SET
Beginning of file
fclose(file*stream)は、指定したファイルを閉じるために使用されます.
fflush(file*stream)は、バッファのデータをファイルにプッシュするために使用されます.
以下に例のプログラムを示します:/*FREAD.C: This program opens a file named FREAD.OUT and * writes 25 characters to the file. It then tries to open * FREAD.OUT and read in 25 characters. If the attempt succeeds, * the program displays the number of actual items read. */#include void main( void ){ FILE *stream; char list[30]; int i, numread, numwritten;/* Open file in text mode: */if( (stream = fopen( "fread.out", "w+t")) != NULL ) { for ( i = 0; i < 25; i++ ) list[i] = (char)('z' - i);/* Write 25 characters to stream */numwritten = fwrite( list, sizeof( char ), 25, stream ); printf( "Wrote %d items/n", numwritten ); fclose( stream ); } else printf( "Problem opening the file/n"); if( (stream = fopen( "fread.out", "r+t")) != NULL ) {/* Attempt to read in 25 characters */numread = fread( list, sizeof( char ), 25, stream ); printf( "Number of items read = %d/n", numread ); printf( "Contents of buffer = %.25s/n", list ); fclose( stream ); } else printf( "File could not be opened/n");}
c++ではofstreamとifstreamでファイルの操作を行うことができます.この場合、ヘッダファイルfstreamを含まなければなりませんが、c++のファイルの操作方法は多くありません.
win 32では
HANDLE CreateFile( LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile
); 
 。。。。
 
BOOL WriteFile( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped
); 
 。。
 
#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void __cdecl _tmain(int argc, TCHAR *argv[])
{
    HANDLE hFile; 
    char DataBuffer[] = "This is a test string.";
    DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
    DWORD dwBytesWritten = 0;

    printf("/n");
    if( argc != 2 )
    {
        printf("ERROR:/tIncorrect number of arguments/n/n");
        printf("%s <file_name>/n", argv[0]);
        return;
    }

    hFile = CreateFile(argv[1],                // name of the write
                       GENERIC_WRITE,          // open for writing
                       0,                      // do not share
                       NULL,                   // default security
                       CREATE_ALWAYS,          // overwrite existing
                       FILE_ATTRIBUTE_NORMAL,  // normal file
                       NULL);                  // no attr. template

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        printf("Could not open file (error %d)/n", GetLastError());
        return;
    }

    _tprintf(TEXT("Writing %d bytes to %s./n"), dwBytesToWrite, argv[1]);

    // This loop would most likely never repeat for this synchronous example.
    // However, during asynchronous writes the system buffer may become full,
    // requiring additional writes until the entire buffer is written.

    while (dwBytesWritten < dwBytesToWrite)
    {
        if( FALSE == WriteFile(hFile,           // open file handle
                               DataBuffer + dwBytesWritten,     // start of data to write
                               dwBytesToWrite - dwBytesWritten, // number of bytes to write
                               &dwBytesWritten, // number of bytes that were written
                               NULL)            // no overlapped structure
          )
        {
            printf("Could not write to file (error %d)/n", GetLastError());
            CloseHandle(hFile);
            return;
        }
    }

    _tprintf(TEXT("Wrote %d bytes to %s successfully./n"), dwBytesWritten, argv[1]);

    CloseHandle(hFile);
}

Example: Open a File for Reading
The following example uses CreateFile to open an existing file for reading and ReadFile to read up to 80 characters synchronously from the file.

In this case, CreateFile succeeds only if the specified file already exists in the current directory. A subsequent call to open this file with CreateFile will succeed if the call uses the same access and sharing modes.

Tip: You can use the file you created with the previous WriteFile example to test this example.


#include <windows.h>
#include <tchar.h>
#include <stdio.h>

#define BUFFER_SIZE 81

void __cdecl _tmain(int argc, TCHAR *argv[])
{
    HANDLE hFile; 
    DWORD dwBytesRead = 0;
    char ReadBuffer[BUFFER_SIZE] = {0};

    printf("/n");
    if( argc != 2 )
    {
        printf("ERROR:/tIncorrect number of arguments/n/n");
        printf("%s <text_file_name>/n", argv[0]);
        return;
    }

    hFile = CreateFile(argv[1],               // file to open
                       GENERIC_READ,          // open for reading
                       FILE_SHARE_READ,       // share for reading
                       NULL,                  // default security
                       OPEN_EXISTING,         // existing file only
                       FILE_ATTRIBUTE_NORMAL, // normal file
                       NULL);                 // no attr. template
 
    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        printf("Could not open file (error %d)/n", GetLastError());
        return; 
    }

    // Read one character less than the buffer size to save room for
    // the terminating NULL character.

    if( FALSE == ReadFile(hFile, ReadBuffer, BUFFER_SIZE-1, &dwBytesRead, NULL) )
    {
        printf("Could not read from file (error %d)/n", GetLastError());
        CloseHandle(hFile);
        return;
    }

    if (dwBytesRead > 0)
    {
        ReadBuffer[dwBytesRead+1]='/0'; // NULL character

        _tprintf(TEXT("Text read from %s (%d bytes): /n"), argv[1], dwBytesRead);
        printf("%s/n", ReadBuffer);
    }
    else
    {
        _tprintf(TEXT("No data read from file %s/n"), argv[1]);
    }

    CloseHandle(hFile);
}