C Way to write an array of strings into a TXT file
There are five file names stored in an array of strings to be saved to disk in a line-by-row write to the TXT file.
Format the file output with fprintf
void Filewrite(){ FILE *fp; char * name[] = {"filen1""file2""file3""file4""file4"}; fp = fopen("E://test.txt""w"); for (int05; i++) { fprintf"%s\n", name[i]); } fclose(fp);}
Write line by row using the Fputs function
char *InputStr="this is ok"; FILE* fp = fopen("C:\\1.txt""wt"); if(fp != NULL) { 0, SEEK_END); fputs(InputStr, fp); fputs("\r\n",fp); fclose(fp); }
Read a string in a TXT file row by line
Text.txt file contents are as follows
file1file2file3file4file4
To read it into a string array
Format input to a file using fscanf
void Fileread(){ int0; *fp; fp = fopen("E://test.txt""r"); char name[6][10]; while(!feof(fp)) { fscanf(fp,"%s", name[i]); printf("%s", name[i]); i++; } fclose(fp);}
C + + mode
#include <fstream>#include <string>#include <iostream>using namespace STD;intMain () {Ifstream in ("Test.txt");stringFileNamestringLineif(in)//have the document{ while(Getline (in, line))Line breaks for each line are not included in//lines{cout<< line << Endl; } }Else //No This file{cout<<"No such file"<< Endl; }return 0;}
Implement file File1, copy to file File2
#include <fstream>#include <string>#include <iostream>using namespace STD;voidFileCopy (Char*file1,Char*file2) {//Best to Judge File1 and File2Ifstream in (FILE1); Ofstream out (file2);stringFileNamestringLine while(Getline (in, line)) {Out << line << Endl; }}intMain () {fileCopy ("1.txt","2.txt");return 0;}
MFC mode
Under the MFC framework, it is recommended to use CString and CFile to handle strings and files, so that there is no coding conversion problem, easy handling and error-prone.
CFile f;f.Open(_T("d:\\txl.txt"),CFile::modeReadWrite);CString wstr;int len = strSum.GetLength();cf.Write(strSum.GetBuffer(len), len);f.Write("\r\n"2);f.Close();
There may be a problem with coding chaos, you can use CS
Read and write string arrays to text TXT file by line