Under MacOS file reading problem

  • Use Xcode to write C ++ programs can be used directly fstream read and write files, as follows:
const char* path1 = [path UTF8String];
string filename = path1; ifstream in(filename,ifstream::in); if(in){
  
string buf;
  
while(getline(in,buf)){
    cout
<<buf<<endl; }
}
else{
  cerr
<<"cannot open this file: "<<filename<<endl;
}

  • If you write App, the absolute path to the file can not be used, you must use relative paths, as follows:
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"question.txt"];
NSString *fileContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  • If the one-time reading of the file size is too large, use NSString save the contents of the file will lose some out of memory, while C ++ is not read by line.

Guess you like

Origin www.cnblogs.com/TD-Lemon1996/p/11078139.html