How to read files into strings in C language and write strings into files

Source: Internet
Author: User

1. Pure C implementation

Copy codeThe Code is 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. Use CFile (MFC base class)

The header file to be included in CFile is Afx. h.

The function prototype for opening a file is as follows:

If (! (Fp. Open (LPCTSTR) m_strsendFilePathName, CFile: modeRead )))

There are multiple modes, commonly used as follows:

ModeRead

ModeWrite

ModeReadWrite

ModeCreate

There are two file types:

TypeBinary

TypeText

You must use typeBinary to read and write non-text files.

Function prototype for reading data:

Virtual UINTRead (void * lpbuf, UINT nCount );

Read the file:

Copy codeThe Code is 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 indispensable
If (fp. Read (tmp, fpLength) <1)
{
Fp. Close ();
Return;
}

// Create a file and write itCopy codeThe Code is as follows: if (! (Fp. Open (LPCTSTR) m_strsendFilePathName,
CFile: modeCreate | CFile: modeWrite | CFile: typeBinary )))
{
Return;
}
Fp. SeekToBegin ();
Fp. write (tmp, fpLength );
Fp. close;

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.