本文實例為大家分享了C語言按行讀寫文件的具體代碼,供大家參考,具體內容如下
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#include <string.h>void my_fputs(char* path){ FILE* fp = NULL; //"w+",讀寫方式打開,如果文件不存在,則創建/ 如果文件存在,清空內容,再寫 fp = fopen(path, "w+"); if (fp == NULL) { //函數參數只能是字符串 perror("my_fputs fopen"); return; } //寫文件 char* buf[] = { "this ", "is a test /n", "for fputs" }; int i = 0, n = sizeof(buf)/sizeof(buf[0]); for (i = 0; i < n; i++) { //返回值,成功,和失敗,成功是0,失敗非0 int len = fputs(buf[i], fp); printf("len = %d/n", len); } if (fp != NULL) { fclose(fp); fp = NULL; }}void my_fgets(char* path){ FILE* fp = NULL; //讀寫方式打開,如果文件不存在,打開失敗 fp = fopen(path, "r+"); if (fp == NULL) { perror("my_fgets fopen"); return; } char buf[100];//char buf[100] = { 0 }; while (!feof(fp))//文件沒有結束 { //sizeof(buf),最大值,放不下只能放100;如果不超過100,按實際大小存放 //返回值,成功讀取文件內容 //會把“/n”讀取,以“/n”作為換行的標志 //fgets()讀取完畢后,自動加字符串結束符0 char* p = fgets(buf, sizeof(buf), fp); if (p != NULL) { printf("buf = %s/n", buf); printf("%s/n", p); } } printf("/n"); if (fp != NULL) { fclose(fp); fp = NULL; }}int main(void){ my_fputs("../003.txt");//上一級地址 my_fgets("../003.txt"); printf("/n"); system("pause"); return 0;}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選