Hàm fgetc đọc 1 kí tự từ file

int fgetc(FILE *stream);

Parameter:

stream: con trỏ file

Remark:

Hàm fgetc( ) đọc 1 kí tự từ file.

  • Hàm fgetc( ) trả về mã ASCII của kí tự đọc được
  • Hàm trả về EOF nếu gặp lỗi hoặc cuối file.

Ví dụ:

#include "stdio.h"
#include "conio.h"


void main()
{
    FILE *fp;
    char forum_name[] = "vncoding.net";
    char s[80];
    char c;
    char *p;
    int n_byte;

    // Print line to file using fputc. 
    p = forum_name;
    if((fp = fopen("D:\\data.txt","w+")) == NULL)
        printf("\nError in opening file");
    else
    {
        while( (*p != '\0') && fputc( *(p++), fp ) != EOF );

        fseek(fp, 0L, SEEK_SET);
        p = s;
        while((c = fgetc(fp)) != EOF)
        {
            *(p++) = c;
        }
        *p = '\0'; // NULL at the end of string
        printf("\n%s", s);

        fclose( fp );
    }
    getch(); 
}

Kết quả:

Hàm fgetc đọc 1 kí tự trong file
File data.txt

Be the first to comment

Leave a Reply