长春市做网站的公司,烟台高端网站建设公司,即时设计网页,中关村手机报价大全手机排行打开函数 fopen 的原型如下。 FILE * fopen(char *filename, char *mode); 返回值#xff1a;打开成功#xff0c;返回该文件对应的 FILE 类型的指针#xff1b;打开失败#xff0c;返回 NULL。 表 2模式含 义说 明r只读文件必须存在#xff0c;否则打开失败w只写若文件存…打开函数 fopen 的原型如下。 FILE * fopen(char *filename, char *mode); 返回值打开成功返回该文件对应的 FILE 类型的指针打开失败返回 NULL。 表 2模式含 义说 明r只读文件必须存在否则打开失败w只写若文件存在则清除原文件内容后写入否则新建文件后写入a追加只写若文件存在则位置指针移到文件末尾在文件尾部追加写人故该方式不 删除原文件数据若文件不存在则打开失败r读写文件必须存在。在只读 r 的基础上加 表示增加可写的功能。下同w读写新建一个文件先向该文件中写人数据然后可从该文件中读取数据a读写在” a”模式的基础上增加可读功能rb二进制读功能同模式”r”区别b表示以二进制模式打开。下同wb二进制写功能同模式“w”。二进制模式ab二进制追加功能同模式”a”。二进制模式rb二进制读写功能同模式r”。二进制模式wb二进制读写功能同模式”w”。二进制模式ab二进制读写功能同模式”a”。二进制模式关闭函数 fclose 的原型如下。 int fclose(FILE *fp); // 函数参数fp:已打开的文件指针。 返回值正常关闭返回否则返回 EOF(-1)。 文件格式化输出函数 fprintf 的函数原型为所在头文件stdio.h int fprintf (文件指针格式控制串输出表列) 函数功能把输出表列中的数据按照指定的格式输出到文件中。返回值输出成功返回输出的字符数输出失败返回一负数 #include stdio.h#define SUCCESS 1
#define FAIL 0
#define FILE_PARH /root/Desktop/data/new/
#define FILE_NAME FILE_PARH test.textint writFile()
{FILE *fp;fp fopen(FILE_NAME, w);if (!fp){return FAIL;}fprintf(fp,this is a test %s\n,- OK);fclose(fp);return SUCCESS;
}
int main(int argc, char* argv[])
{int iRes SUCCESS;iRes writFile();return iRes;
}运行结果
[root192 new]# cat ./test.text
this is a test - OK C 语言程序中常使用 fseek 函数移动文件读写位置指针 int fseek(FILE *fp, long offset, int origin); 函数功能把文件读写指针调整到从 origin 基点开始偏移 offset 处即把文件读写指针移动到 originoffset 处。 基准位置 origin 有三种常量取值SEEK_SET、SEEK_CUR 和 SEEK_END取值依次为 012。 SEEK_SET:文件开头即第一个有效数据的起始位置。 SEEK_CUR当前位置。 SEEK_END:文件结尾即最后一个有效数据之后的位置。 #include stdio.h#define SUCCESS 1
#define FAIL 0
#define FILE_PARH /root/Desktop/data/new/
#define FILE_NAME FILE_PARH a.textint writeBeginFile()
{int iRes SUCCESS;FILE *fp;fp fopen(FILE_NAME, w);if (!fp){return FAIL;}fprintf(fp,this is a test content %s\n,- OK);fprintf(fp,this is a test content %s\n,- OK);fseek(fp, 0, SEEK_SET); //文件头fprintf(fp, %s\n, This the file begin);fseek(fp, 0, SEEK_END); //文件尾fprintf(fp, %s\n, This the file end);fclose(fp);return iRes;}int main(int argc, char* argv[])
{int iRes SUCCESS;iRes writeBeginFile();return iRes;
}运行结果 [root192 new]# cat a.textThis the file beginnt - OKthis is a test content - OKThis the file end 转载于:https://www.cnblogs.com/mingyue605/p/10587672.html