char *gets(char *buffer);
Parameter:
buffer: con trỏ kiểu char lưu string đầu vào
Remark:
Hàm gets( ) đọc string từ đầu vào stdin (bàn phím) và lưu nó trong buffer. - Hàm gets( ) trả về con trỏ trỏ tới vùng nhớ lưu string, nếu đọc thành công - Hàm gets() trả về NULL, nếu đọc không thành công
Ví dụ:
#include "conio.h"
#include <stdio.h>
void main( void ) {
char line[21]; // room for 20 chars + '\0'
gets( line ); // C4996
// Danger: No way to limit input to 20 chars.
// Consider using gets_s instead.
printf( "The line entered was: %s\n", line ); getch();
}
Kết quả:
vu hong viet
vncoding.net Page 41
int fflush( FILE *stream );
Parameter:
stream: con trỏ file
Remark:
- Hàm fflush( ) “làm sạch” stream( stdin: đầu vào, stdout: đầu vào).
- Hàm fflush( ) trả về 0, nếu stream được “làm sạch” thành công. Và trả về EOF nếu lỗi xuất hiện.
Ví dụ:
#include "conio.h"
#include <stdio.h>
void main( void ) {
int integer; char string[81];
// Read each word as a string.
printf( "Enter a sentence of four words with scanf: " ); for( integer = 0; integer < 4; integer++ )
{
scanf( "%s", string, sizeof(string) ); printf( "%s\n", string );
}
// You must flush the input buffer before using gets.
// fflush on input stream is an extension to the C standard
fflush( stdin );
printf( "Enter the same sentence with gets: " ); gets(string);
printf( "%s\n", string ); getch();
}
vncoding.net Page 42
Enter a sentence of four words with scanf: this is a test this
is a test
Enter the same sentence with gets: this is a test this is a test
vncoding.net Page 43
Hàm thao tác 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. Đ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