Deep C Language The solution of reading a file into a string and writing a string to a file _c language

Source: Internet
Author: User
Tags function prototype

1. Pure C Implementation

Copy Code code as follows:

FILE *FP;
if (fp = fopen ("Example.txt", "rb") = = NULL)
{
Exit (0);
}
Fseek (FP, 0, Seek_end);
int fileLen = Ftell (FP);
Char *tmp = (char *) malloc (sizeof (char) * fileLen);
Fseek (FP, 0, Seek_set);
Fread (TMP, FileLen, sizeof (char), FP);
Fclose (FP);
for (int i = 0; i < FileLen; ++i)
{
printf ("%d", tmp[i]);
}
printf ("\ n");

if (fp = fopen ("Example.txt", "wb") = = NULL)
{
Exit (0);
}
Rewind (FP);
Fwrite (TMP, FileLen, sizeof (char), FP);
Fclose (FP);
Free (TMP);


2. Using CFile (MFC base Class)

CFile need to include header files for Afx.h

The function prototype for opening the file is as follows

if (!) ( Fp. Open ((LPCTSTR) m_strsendfilepathname,cfile::moderead))

There are a variety of patterns, commonly used are as follows:

Moderead

Modewrite

Modereadwrite

Modecreate

There are two kinds of file types:

Typebinary

TypeText

Read and write non-text files must use Typebinary

function prototypes for reading data:

Virtual Uintread (void*lpbuf, UINT ncount);


Read the file:

Copy Code code as follows:

CFile FP;
if (!) ( Fp. Open ((LPCTSTR) m_strsendfilepathname,cfile::moderead))
{
Return
}
Fp. Seektoend ();
Unsignedint fplength = fp. GetLength ();
Char *tmp= new Char[fplength];
Fp.    Seektobegin (); This sentence is essential
if (FP. Read (Tmp,fplength) < 1)
{
Fp. Close ();
Return
}

New file and write to
Copy Code code as follows:

if (!) ( Fp. Open ((LPCTSTR) M_strsendfilepathname,
Cfile::modecreate | Cfile::modewrite | cfile::typebinary)))
{
Return
}
Fp. Seektobegin ();
Fp.write (tmp,fplength);
Fp.close;

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.