C language file Read and write example (C language file operation) _c language

Source: Internet
Author: User

Method:

Copy Code code as follows:

Long filesize (char* filename);
char* file_get_contents (char* filename);
void file_put_contents (char* filename, char* data);

Example:

Copy Code code as follows:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Long filesize (char* filename);
char* file_get_contents (char* filename);
void file_put_contents (char* filename, char* data);

int main () {
printf ("%s\n", "----------------Begin---------------");
char* filename = "/tmp/tmp.txt";
File_put_contents (filename, "http://www.jb51.net");
char* data = file_get_contents (filename);
printf ("Fd::%s\n", data);
printf ("%s\n", "----------------End-----------------");
return 0;
}

Long filesize (char* filename) {
Long length;
file* stream = fopen (filename, "RB");
if (!stream) return 0L;
Fseek (Stream, 0L, seek_end);
Length = Ftell (stream);
Fclose (stream);
return length;
}

char* file_get_contents (char* filename) {
file* fp = fopen (filename, "RB");
if (!FP) {
printf ("%s\n", "The file can not be opened.");
Exit (0);
}

Long length = filesize (filename);
char* buffer = (char*) malloc (length);
Char buf[1024];
memset (buffer, 0x00, sizeof (buffer));
Fseek (FP, 0L, Seek_set);
while (Fgets (BUF, 1024, FP)!= NULL)
strcat (buffer, buf);

Fclose (FP);
return buffer;
}

void file_put_contents (char* filename, char* data) {
file* fp = fopen (filename, "w+");
if (!FP) {
printf ("The file can not be opened.\n");
Exit (1);
}
Fputs (data, FP);
Fclose (FP);
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.