Hàm fopen mở file

FILE *fopen( const char *filename,const char *mode);

Parameter:

filename: tên file (bao gồm cả đường dẫn tới file)

mode: các chế độ open khác nhau

“r” : mở để đọc. Nếu file không tồn tại hoặc không tìm thấy file, hàm fopen() trả về NULL.

“w” : mở để ghi. Nếu file đã tồn tại thì nội dung trong file sẽ bị xóa.

“a” : mở để ghi tiếp vào cuối file. Nếu file không tồn tại, file sẽ được tạo mới

“r+”: mở để đọc và ghi (có thể update nội dung bất kì vị trí nào trong file). Điều kiện: file phải tồn tại.

“w+” : mở file trống để đọc và ghi. Nếu file đã tồn tại, nội dung sẽ bị xóa.

“a+” : mở để đọc và ghi tiếp vào cuối file. Sẽ tạo file mới nếu file không tồn tại

Remark:

  • Hàm fopen( ) dùng để mở file để đọc/ghi/
  • Hàm fopen( ) sẽ trả về con trỏ FILE nếu mở thành công, và trả về NULL nếu xảy ra lỗi (không tìm thấy file, file không tồn tại,..)

Ví dụ:

#include "conio.h"
#include <stdio.h>

void main( void )
{
    FILE *stream, *stream2;
    //Open for reading
    if( (stream = fopen( "vncoding.c", "r" )) == NULL )
        printf( "The file 'vncoding.c' was not opened\n" );
    else
        printf( "The file 'vncoding.c' was opened\n" );

    // Open for write 
    if( (stream2 = fopen( "log.txt", "w+" )) == NULL )
        printf( "The file 'log.txt' was not opened\n" );
    else
        printf( "The file 'log.txt' was opened\n" );
    getch();
}

Kết quả:

Hàm fopen mở và tạo file

Be the first to comment

Leave a Reply