The C language implements reading and writing files by line

  • 2020-06-19 11:20:13
  • OfStack

This article shares the specific code of C language reading and writing files by line for your reference. The specific content is as follows


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void my_fputs(char* path)
{
 FILE* fp = NULL;

 //"w+" , open in read/write mode, and create if the file does not exist \
   If the file exists, clear the contents before writing 
 fp = fopen(path, "w+");
 if (fp == NULL)
 {
 // Function arguments can only be strings 
 perror("my_fputs fopen");
 return;
 }

 // Write files 
 char* buf[] = { "this ", "is a test \n", "for fputs" };
 int i = 0, n = sizeof(buf)/sizeof(buf[0]);
 for (i = 0; i < n; i++)
 {
 // Return value, successful , And failure, success is 0 , failure 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;
 // Open with read/write mode. If the file does not exist, open failed 
 fp = fopen(path, "r+");
 if (fp == NULL)
 {
 perror("my_fgets fopen");
 return;
 }

 char buf[100];//char buf[100] = { 0 };
 while (!feof(fp))// File does not end 
 {
 //sizeof(buf), Maximum value, can not put only put 100 ; If not more than 100 Store according to actual size 
 // Return value, successfully read file contents 
 // The" \n "To" \n "As a line break sign 
 //fgets() After reading, the string terminator is automatically added 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");// on 1 Level address 

 my_fgets("../003.txt");

 printf("\n");
 system("pause");
 return 0;
}

Related articles: