Create and delete:
// Create a file manager
Nsfilemanager * filemanager = [nsfilemanager defaultmanager];
// Obtain the path
// Obtain the path of the nsdocumentdirectory Parameter
Nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes );
Nsstring * documentsdirectory = [paths objectatindex: 0]; // The path required for the path.
// Change to the directory to be operated
[Filemanager changecurrentdirectorypath: [documentsdirectory stringbyexpandingtildeinpath];
// Create the file filename file name and the content of the contents file. If there is no content at the beginning, you can set it to nil, the attribute of the attributes file, initially Nil
[Filemanager createfileatpath: @ "FILENAME" Contents: Nil attributes: Nil];
// Delete the object to be deleted
[Filemanager removeitematpath: @ "creatednewfile" error: Nil];
Write Data:
// Obtain the file path
Nsstring * Path = [documentsdirectory stringbyappendingpathcomponent: @ "FILENAME"];
// Data to be written
Nsstring * temp = @ "Hello Friend ";
Int data0 = 100000;
Float data1 = 23.45f;
// Create a data buffer
Nsmutabledata * Writer = [nsmutabledata alloc] init];
// Add the string to the buffer
[Writer appenddata: [temp datausingencoding: nsutf8stringencoding];
// Add other data to the buffer
[Writer appendbytes: & data0 length: sizeof (data0)];
[Writer appendbytes: & data1 length: sizeof (data1)];
// Write the buffered data to the file
[Writer writetofile: path atomically: Yes];
[Writer release];
Read data:
Int gdata0;
Float gdata1;
Nsstring * gdata2;
Nsdata * reader = [nsdata datawithcontentsoffile: path];
Gdata2 = [[nsstring alloc] initwithdata: [READER subdatawithrange: nsmakerange (0, [temp length])]
Encoding: nsutf8stringencoding];
[READER getbytes: & gdata0 range: nsmakerange ([temp length], sizeof (gdata0)];
[READER getbytes: & gdata2 range: nsmakerange ([temp length] + sizeof (gdata0), sizeof (gdata1)];
Nslog (@ "gdata0: % @ gdata1: % I gdata2: % F", gdata0, gdata1, gdata2 );
Read files from the project:
When reading data, you should look at the original file format of the file to be read, whether it is a bytecode or text. I often need to read the bytecode from the file again, so I am writing the method of reading byte files.
// The variable used to store data. Because it is a byte, It is uint8.
Uint8 B = 0;
// Obtain the file path
Nsstring * Path = [[nsbundle mainbundle] pathforresource: @ "FILENAME" oftype: @ ""];
// Obtain data
Nsdata * reader = [nsdata datawithcontentsoffile: path];
// Obtain the number of bytes
Int length = [READER length];
Nslog (@ "---> byteslength: % d", length );
For (INT I = 0; I <length; I ++) {// read data [READER getbytes: & B Range: nsmakerange (I, sizeof (B)]; nslog (@ "---> data % d: % d", I, B );
}