C語言實現按行讀寫檔案
阿新 • • 發佈:2020-01-07
本文例項為大家分享了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; }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。