The solution to reading a file into a string and writing a string to a file in C
- 2020-04-01 23:32:51
- OfStack
1. Pure C implementation
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 that the CFile needs to contain is afx.h
The function prototype to open the file is as follows
If (! (fp) Open ((LPCTSTR) m_strsendFilePathName CFile: : modeRead)))
There are a variety of modes, commonly used as follows:
modeRead
modeWrite
modeReadWrite
modeCreate
There are two file types:
typeBinary
typeText
Always use typeBinary to read or write non-text files
Function prototype for reading data:
Virtual UINTRead (void * lpbuf, UINT nCount);
Read the document:
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 is essential
if(fp.Read(tmp,fpLength) < 1)
{
fp.Close();
return;
}
// new file and write
if(!(fp.Open((LPCTSTR)m_strsendFilePathName,
CFile::modeCreate | CFile::modeWrite |CFile::typeBinary)))
{
return;
}
fp.SeekToBegin();
fp.write(tmp,fpLength);
fp.close;