Linux opens a file and writes a string, reading the corresponding file information--fopen ()/fwrite ()/fread ()

Source: Internet
Author: User
Tags fread

Linux opens a file and writes a string that reads the corresponding file information
in Linux, using the C language, use the fopen () function to open a file (if no file exists, create a new one, such as Data/test.dat),
and use the

fwrite () writes the appropriate string to it, each time the input writes are wrapped, and finally the corresponding information is read with Fread ().
the corresponding code is as follows: TEST.c
/*test.c:create a File:write a string to the file */#include <stdio.h> #include <string.h> #include <std   lib.h> #define MAX 128intmain () {FILE *FP = NULL;    Notice char *filepath = "Data/test.dat";    Char stringdes[] = "Hello World";    Stringdes[strlen (stringdes)] = ' n '; Char buf[max];/* open a file:file *fopen (const char *path, const char *mode);    */#if 1 fp = fopen (FilePath, "at+");        if (NULL = = fp) {perror ("FP");    return-1; } printf ("File Open success! \ n "); #endif/* Write data block to a file:size_t fwrite (const void* buffer, size_t size, size_t count, file* Strea   m);    */int i;        for (i = 0; I <= 2; i++) {fwrite (Stringdes,strlen (Stringdes), 1, FP);        Fwrite ("\ n", 1, 1, FP);    Fflush (FP);    } printf ("File set start \ n");  Fseek (Fp,0,seek_set);    Set start File Fread (Buf,strlen (stringdes), 1,FP);    Buf[strlen (stringdes)] = ' n ';    printf ("buf =%s \ n", buf); Fclose (FP);}

the contents of Test.dat are as follows:
[email protected]:~/openandwritefile/zywtest/data# vim Test.dat
Hello World, Hello World,
Hello world
~                                        ,         &NB Sp                          ,         &NB Sp                                
~                                                  ,         &N Bsp                          ,         &NB Sp                        
~

Linux opens a file and writes a string, reading the corresponding file information--fopen ()/fwrite ()/fread ()

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.