程序中有时候,我们需要生成多个文件名连续的文件,那么我们就需要用到函数
int sprintf( char *buffer, const char *format [, argument] ... );
int swprintf( wchar_t *buffer, const wchar_t *format [, argument] ... );
Routine | Required Header | Compatibility |
sprintf | <stdio.h> | ANSI, Win 95, Win NT |
swprintf | <stdio.h> or <wchar.h> | ANSI, Win 95, Win NT |
Libraries
LIBC.LIB | Single thread static library, retail version |
LIBCMT.LIB | Multithread static library, retail version |
MSVCRT.LIB | Import library for MSVCRT.DLL, retail version |
Return Value
sprintf returns the number of bytes stored in buffer, not counting the terminating null character. swprintf returns the number of wide characters stored in buffer, not counting the terminating null wide character.
Parameters
buffer
Storage location for output
format
Format-control string
argument
Optional arguments
/*批量生成文件名为 Beauty01.txt,Beauty02.txt,Beauty03.txt......
内容写文件名
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned char file_name[15];
unsigned i;
for(i=1;i<=9;i++)
{
sprintf(file_name,"Beauty%02d.txt",i);
freopen(file_name,"wb",stdout);
printf("%s/n",file_name);
}
return 0;
}
读取文本信息,并且以追加的方式写入
#include<stdio.h>
#include<stdlib.h>
void isOpenFile(FILE *fp)
{
if(NULL == fp) //打开文件失败
{
printf("/nError Open the File!/n");
getch();
exit(1);
}
return;
}
int main()
{
FILE *my_file;
my_file = fopen("G://cpp//test.txt","rb");
isOpenFile(my_file);
char ch;
ch = fgetc(my_file);
while((0 == feof(my_file)))
{
putchar(ch);
ch = fgetc(my_file);
}
fclose(my_file); //关闭文件
/************************************************/
my_file = fopen("G://cpp//test.txt","ab+");
isOpenFile(my_file);
int i;
for(i=0;i<100;i++)
{
fputc(i,my_file);
}
rewind(my_file);
ch = fgetc(my_file);
while((0 == feof(my_file)))
{
printf("%d ",ch);
ch = fgetc(my_file);
}
fclose(my_file);
/*************************************************/
putchar(-43); //test
putchar(-30);
return 0;
}
如何获得未知文件的大小
Moves the file pointer to a specified location.
int fseek( FILE *stream, long offset, int origin );
orgin:
SEEK_CUR
Current position of file pointer
SEEK_END
End of file
SEEK_SET
Beginning of file
Gets the current position of a file pointer.
long ftell( FILE *stream );
Code:
#include<stdio.h>
#include<stdlib.h>
void isOpenFile(FILE *fp)
{
if(NULL == fp) //打开文件失败
{
printf("/nError Open the File!/n");
getch();
exit(1);
}
return;
}
int main()
{
FILE *my_file;
my_file = fopen("G://cpp//test.txt","rb");
isOpenFile(my_file);
fseek(my_file,0,SEEK_END);
int Length = ftell(my_file);
rewind(my_file);
printf("%d/n",Length);
fclose(my_file);
return 0;
}