先以只写的方式打开file.dat,再把字符串s中的字符保存到这个磁盘中。
FILE* f
FILE是变量类型,实际上是C语言定义的标准数据结构,用于文件。
FILE* f是声明,声明f是指针,用来指向FILE类型的对象。
f = fopen("1.txt","r");fopen标准函数打开磁盘文件1.txt,用于读,返回指针,指向FILE类型的对象。
fscanf用于从文件读入数据,scanf从键盘输入数据。
fprintf是C/C++中的一个格式化写—库函数;其作用是格式化输出到一个流/文件中;格式为:int fprintf( FILE *stream, const char *format, ... );
若成功则返回输出字符数,若输出出错则返回负值。
例如:
int
i = 10;
stream =
fopen
(
"fprintf.out"
,
"w"
);
fprintf
( stream,
"%d\n"
, i );
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
# define N 100
int main()
{
FILE* f;
int i = 0;
char ch;
char s[N] = "Welcome!";
if ((f = fopen("file.dat","w"))==NULL)
{
printf("cannot open file.dat\n");
exit(0);
}
while (s[i])
{
ch = s[i];
fputc(s[i],f);
putchar(ch);
i++;
}
fclose(f);
system("pause");
return 0;
}