对文件的读和写是最常用的文件操作。在C语言中提供了多种文件读写的函数:
·字符读写函数 :fgetc和fputc
·字符串读写函数:fgets和fputs
·数据块读写函数:fread和fwrite
·格式化读写函数:fscanf和fprinf
随着每次数据的读取,文件流指针fp都作相应的移动
使用以上函数都要求包含头文件stdio.h。例子都来自msdn
1 fprintf——Print formatted data to a stream
#include #include FILE *stream;
void main( void )
{
int i = 10;
double fp = 1.5;
char s[] = "this is a string";
char c = '/n';
stream = fopen( "fprintf.out", "w" );
fprintf( stream, "%s%c", s, c );
fprintf( stream, "%d/n", i );
fprintf( stream, "%f/n", fp );
fclose( stream );
system( "type fprintf.out" );
}
Output
this is a string
10
1.500000
2 fscanf——Read formatted data from a stream
#include FILE *stream;
void main( void )
{
long l;
float fp;
char s[81];
char c;
stream = fopen( "fscanf.out", "w+" );
if( stream == NULL )
printf( "The file fscanf.out was not opened/n" );
else
{
fprintf( stream, "", "a-string",
65000, 3.14159, 'x' );
/* Set pointer to beginning of file: */
( stream, 0L, SEEK_SET );
/* Read data back from file: */
fscanf( stream, "%s", s );
fscanf( stream, "%ld", &l );
fscanf( stream, "%f", &fp );
fscanf( stream, "%c", &c );
/* Output data read: */
printf( "%s/n", s );
printf( "%ld/n", l );
printf( "%f/n", fp );
printf( "%c/n", c );
fclose( stream );
}
}
Output
a-string
65000
3.141590
x
3 fread——Reads data from a stream
4 fwrite——Writes data to a stream
读数据块函数调用的一般形式为:
fread(buffer,size,count,fp);
写数据块函数调用的一般形式为:
fwrite(buffer,size,count,fp);
其中:
buffer 是一个指针,在fread函数中,它表示存放输入数据的首地址。在fwrite函数中,它表示存放输出数据的首地址。
size 表示数据块的字节数。
count 表示要读写的数据块块数。
fp 表示文件指针。
5 fgets 没有看出与fread太大的区别,除了fread可以处理string外的其他不同文件的数据类型
6 fputs
7 fgetc fputs
从键盘输入一行字符,写入一个文件,再把该文件内容读出显示在屏幕上。
#i nclude
main()
{
FILE *fp;
char ch;
if((fp=fopen("d://jrzh//example//string","wt+"))==NULL)
{
printf("Cannot open file strike any key exit!");
getch();
exit(1);
}
printf("input a string:/n");
ch=getchar();
while (ch!='/n')
{
fputc(ch,fp);
ch=getchar();
}
rewind(fp); //Repositions the file pointer to the beginning of a file
ch=fgetc(fp);
while(ch!=EOF)
{
putchar(ch);
ch=fgetc(fp);
}
printf("/n");
fclose(fp);
}
这篇博客详细介绍了C语言中进行文件读写的各种函数,包括字符读写、字符串读写、数据块读写及格式化读写。通过实例展示了如何使用fscanf和fprintf进行格式化输入输出,以及fread和fwrite进行数据块的读写操作。同时,还提到了fgetc、fputc、fgets和fputs等基础文件操作函数的使用,并给出了将文件内容读入并输出到屏幕的示例。
689

被折叠的 条评论
为什么被折叠?



