In this article, we will introduce in detail how to obtain files in C ++. For those who have just been familiar with the C ++ programming language, the content introduced in this article can help them solve some of the problems they often encounter in file operations.
- /*read File*/
- char *txt = NULL;
- long txtlen;
- //seek to file end to calculate file length
- fseek(fp,0,SEEK_END);
- txtlen=ftell(fp);
- //rewind to file start
- rewind(fp);
- //read from file
- txt = new char[txtlen + 1];
- if (txt != NULL)
- {
- fread(txt,sizeof(char),txtlen,fp);
- txt[txtlen]='\0';
- fv.setData(txt);
- }
- //close file and destroy temp array
- fclose(fp);
- if(txt!=NULL)
- {
- delete []txt;
- txt = NULL;
- }
C ++:
- /*read File*/
- ifstream in(filesrc);
- if(in.fail())
- {
- printf("open file failed!\n");
- }
- else
- {
- string strtmp;
- while (getline(in,strtmp))
- {
- fv.getData()+=strtmp;
- fv.getData()+='\n';
- }
- in.close();
- }
The above section describes how to obtain files in C ++.