C语言
顺序读写
fputs fgets
#include <stdio.h>
#include <stdlib.h>
#define MAX 1024
int main ( void )
{
FILE * fp;
char buffer[ MAX] ;
if ( ( fp = fopen ( "lines.txt" , "w" ) ) == NULL )
{
printf ( "打开文件失败!\n" ) ;
exit ( EXIT_FAILURE) ;
}
fputs ( "Line one :I Love The World\n" , fp) ;
fputs ( "Line two :I Love Yoona\n" , fp) ;
fputs ( "Line three :Yoona == The World" , fp) ;
fclose ( fp) ;
if ( ( fp = fopen ( "lines.txt" , "r" ) ) == NULL )
{
printf ( "打开文件失败!\n" ) ;
exit ( EXIT_FAILURE) ;
}
while ( ! feof ( fp) )
{
fgets ( buffer, MAX, fp) ;
printf ( "%s" , buffer) ;
}
return 0 ;
}
fprint fscanf
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ( void )
{
FILE * fp;
struct tm * p;
time_t t;
time ( & t) ;
p = localtime ( & t) ;
if ( ( fp = fopen ( "date.txt" , "w" ) ) == NULL )
{
printf ( "打开文件失败!\n" ) ;
exit ( EXIT_FAILURE) ;
}
fprintf ( fp, "%d-%d-%d" , 1900 + p-> tm_year, 1 + p-> tm_mon, p-> tm_mday) ;
fclose ( fp) ;
int year, month, day;
if ( ( fp = fopen ( "date.txt" , "r" ) ) == NULL )
{
printf ( "打开文件失败!\n" ) ;
exit ( EXIT_FAILURE) ;
}
fscanf ( fp, "%d-%d-%d" , & year, & month, & day) ;
printf ( "%d-%d-%d\n" , year, month, day) ;
fclose ( fp) ;
return 0 ;
}
fwrite fread
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Date
{
int year;
int month;
int day;
} ;
struct Book
{
char name[ 40 ] ;
char author[ 40 ] ;
char publisher[ 40 ] ;
struct Date date;
} ;
int main ( void )
{
FILE * fp;
struct Book * book_for_write, * book_for_read;
book_for_write = ( struct Book * ) malloc ( sizeof ( struct Book) ) ;
book_for_read = ( struct Book * ) malloc ( sizeof ( struct Book) ) ;
if ( book_for_write == NULL || book_for_read == NULL )
{
printf ( "内存分配失败! \n" ) ;
exit ( EXIT_FAILURE) ;
}
strcpy ( book_for_write-> name, "《带你学C带你飞》" ) ;
strcpy ( book_for_write-> author, "Yoona" ) ;
strcpy ( book_for_write-> publisher, "清华大学出版社" ) ;
book_for_write-> date. year = 2021 ;
book_for_write-> date. month = 1 ;
book_for_write-> date. day = 22 ;
if ( ( fp = fopen ( "file.txt" , "w" ) ) == NULL )
{
printf ( "打开文件失败!\n" ) ;
exit ( EXIT_FAILURE) ;
}
fwrite ( book_for_write, sizeof ( struct Book) , 1 , fp) ;
fclose ( fp) ;
if ( ( fp = fopen ( "file.txt" , "r" ) ) == NULL )
{
printf ( "打开文件失败!\n" ) ;
exit ( EXIT_FAILURE) ;
}
fread ( book_for_read, sizeof ( struct Book) , 1 , fp) ;
printf ( "书名:%s\n" , book_for_read-> name) ;
printf ( "作者:%s\n" , book_for_read-> author) ;
printf ( "出版社:%s\n" , book_for_read-> publisher) ;
printf ( "出版日期:%d-%d-%d\n" , book_for_read-> date. year, book_for_read-> date. month, book_for_read-> date. day) ;
fclose ( fp) ;
return 0 ;
}