how to read a file from documents directory - file

i hav to read the file with name myname.plist from documents directory .....i want to store the content of the file to string....

Something like this should do:
/* Find the documents directory. */
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentsDirectory, NSUserDomainMask, YES/*expand tilde*/);
NSAssert([paths count] > 0,
#"%s: No user document directory found!", __func__);
NSString *documentsDir = [paths objectAtIndex:0U];
/* Build the file path. */
NSString *name = [#"myname" stringByAppendingPathExtension:"plist"];
NSString *path = [documentsDir stringByAppendingPathComponent:name];
/* Read in the file content. */
NSError *error = nil;
NSStringEncoding enc;
NSString *content = [NSString
stringWithContentsOfFile:path
usedEncoding:&enc
error:&error];
if (!content) {
NSLog(#"%s: Error reading content of \"%#\": %#", __func__, path, error);
}

Related

How to get file in folder in batch process?

I have to get file in a folder. My process can work in Batch.
My code is this:
Io file;
FileIoPermission perm;
int handle;
Filename fileName;
[handle, filename] = WINAPI::findFirstFile( myFilePatch + "\\*.txt");
fileOpen = strFmt (myFilePatch + "\\" + filename);
if (filename)
{
perm = new FileIoPermission(filename, 'r');
perm.assert();
file = new TextIo(filename, 'r', 65001);
}
//etc... other code
// I go on to find another file
filename = WinAPI::findNextFile(handle);
fileOpen = strFmt (myFilePatch + "\\" + filename);
if (filename)
{
// open file....
}
My problem is for WinAPI.findFirstFile and WinAPI::findNextFile I have an error.
How can I search in a folder,in batch process, the files ?
Thansk all,
enjoy!
Use System.IO.DirectoryInfo and loop through the files with a for-loop. Just replace the folder path below with your folder' location, and it will generate a list of all the files inside the folder.
static void loopDirectory(Args _args)
{
System.IO.DirectoryInfo directory;
System.IO.FileInfo[] files;
System.IO.FileInfo file;
InteropPermission permission;
Filename tmpFilePath;
Filename tmpFileNameShort;
Filename tmpFileExt;
str fileNameTemp;
counter filesCount;
counter loop;
permission = new InteropPermission(InteropKind::ClrInterop);
permission.assert();
directory = new System.IO.DirectoryInfo(#"C:\Users...");
files = directory.GetFiles();
filesCount = files.get_Length();
for (loop = 0; loop < filesCount; loop++)
{
file = files.GetValue(loop);
fileNameTemp = file.get_FullName();
[tmpFilePath, tmpFileNameShort, tmpFileExt] = fileNameSplit(fileNameTemp);
info(tmpFileNameShort);
}
CodeAccessPermission::revertAssert();
}

Replace substring into a string using objective C

I am trying to replace my custom IP address with the existing URL IP address. How can replace the my IP address with the existing IP. Please find the code snippet below
- (IBAction)btnSubmit:(UIButton *)sender {
NSString *ipAdd = [_txtIPAddress text];
NSLog(#"My entered IP Address is %#", ipAdd);
NSLog(#"Current pointing server value is %#", [ConnManager activeEndpoint]);
NSLog([App appDelegate].isConfigured ? #"Yes" : #"No");
NSArray *listItems = [[ConnManager activeEndpoint] componentsSeparatedByString:#"/"];
ConnManager *conn = [[ConnManager alloc] init];
NSMutableString *configuredUrl = nil;
[configuredUrl setString:#""];
for ( NSInteger i =0; i < listItems.count; i++) {
if(i != 2) {
NSMutableString * arrayElement = [(NSMutableString*)listItems objectAtIndex:i];
NSMutableString *str = [NSMutableString stringWithFormat: #"%#/", arrayElement];
[configuredUrl appendString:str];
} else {
NSMutableString *configstr = [NSMutableString stringWithFormat: #"%#", ipAdd];
NSLog(#"ConfigString %#", configstr);
//How to replace the my ip address with the array index[2]
configuredUrl = [configuredUrl stringByAppendingFormat:configstr];
NSLog(#"Configured Url after apppending %#", configuredUrl);
Thanks in advance
Try this shorter version, it replaces everything after the line
NSLog([App appDelegate].isConfigured ? #"Yes" : #"No");
NSMutableArray *listItems = [[[ConnManager activeEndpoint] pathComponents] mutableCopy];
listItems[2] = ipAdd;
NSString *configuredUrl = [NSString pathWithComponents:listItems];
NSLog(#"%#", configuredUrl);
or, if activeEndpoint is an URL, still easier
NSURL *url = [NSURL URLWithString:[ConnManager activeEndpoint]];
NSString *configuredURL = [[[NSURL alloc] initWithScheme:[url scheme] host:ipAdd path:[url path]] absoluteString];
It is often easier to leave the parsing of URLs to a system class. If you can, I would suggest using NSURLComponents. For example:
NSURLComponents *URLComponents =
[NSURLComponents componentsWithString:[ConnManager activeEndpoint]];
URLComponents.host = [_txtIPAddress text];
NSString *configuredURL = URLComponents.string;

How to choose an array (column) from a given file.txt? (stringByAppendingPathComponent) Xcode

I am trying to pick an array (column) from a given file that contains arrays of numbers e.g:
2012-09-02 16:27:15.010 SMA -0.818863 0.286575 0.206177 -0.108286 -0.231033 -0.303317
2012-09-02 16:27:15.017 SMA -1.024597 0.380875 0.456131 -0.282619 -0.123060 -0.048027
2012-09-02 16:27:15.023 SMA -0.754196 0.417053 1.165237 -0.010996 -0.078193 0.594972
2012-09-02 16:27:15.030 SMA -0.674835 0.486038 1.487640 0.061529 -0.008288 0.825637
here is my code, but it's giving nothing:
NSString* filePath = #"/Users/bahmadios/Documents/Xcode/selectArray/selectArray/Bus.txt";//file path...
NSString* fileRoot = [[NSBundle mainBundle]
pathForResource:filePath ofType:#"txt"];
// read everything from text
NSString* fileContents =
[NSString stringWithContentsOfFile:fileRoot
encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#", fileContents);
// first, separate by new line
NSArray* allLinedStrings =
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
NSLog(#"%#", allLinedStrings);
// then break down even further
NSString* strsInOneLine =
[allLinedStrings objectAtIndex:0];
NSLog(#"%#", strsInOneLine);
// choose whatever input identity you have decided. in this case ;
NSArray *array = [ strsInOneLine componentsSeparatedByString:#" "];
if (array.count > 3) {
NSLog(#"---- %#", array[3]);
and I am getting:
2014-05-20 23:26:52.226 selectArray[5734:907] ---- (null)
2014-05-20 23:26:52.227 selectArray[5734:907] (null)
2014-05-20 23:26:52.228 selectArray[5734:907] (null)
2014-05-20 23:26:52.228 selectArray[5734:907] (null)
2014-05-20 23:26:52.229 selectArray[5734:907] ---- (null)
What is wrong?
I'm not sure you need the line that creates strsInOneLine. The following works for me
NSString *filePath = ...;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
[lines enumerateObjectsUsingBlock:^(NSString *line, NSUInteger idx, BOOL *stop) {
NSArray *components = [line componentsSeparatedByString:#" "];
if (components.count > 3) {
NSLog(#"---- %#", components[3]);
}
}];

Memory leak : How to stop?

I am using NSObject class to get all the data from a database. When I call that function it will show a memory leak where I assign a string using stringWithFormat. I think when we use this method we should not have to release that string so why does it show a memory leak?
Thanks in advance. :)
- (void) Allnote
{
[app.NoteArray removeAllObjects];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Notes.sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT * From note" ];
const char *sql = [querySQL UTF8String];
sqlite3_stmt *searchStatement;
if (sqlite3_prepare_v2(database, sql, -1, &searchStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(searchStatement) == SQLITE_ROW)
{
noteClass *noteObj = [[noteClass alloc]init];
noteObj.noteTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)]; // at this place
noteObj.noteContent = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 1)]; // at this place
NSNumber *noteId = [NSNumber numberWithInt:sqlite3_column_int(searchStatement, 2)];
noteObj.noteId = [NSString stringWithFormat:(#"%#"),noteId]; // at this place
files=noteObj.noteTitle;
filescont=noteObj.noteContent;
[app.NoteArray addObject:noteObj];
[noteObj release];
}
}
sqlite3_finalize(searchStatement);
}
sqlite3_close(database);
}
See, stringWithFormatis a factory method means that it has autorelease in its definition, that's why u r getting memory issue. But, that is not an issue.its 100% perfect.
If you aren't apply a format, then why use stringWithFormat
NSString *querySQL = [NSString stringWithFormat:#"SELECT * From note" ];
Is the same as:
NSString *querySQL = #"SELECT * From note";
And you are correct, you do not have te release them.
I am responding in addition to Surya Kant's answer.
It was not a problem with that. But still if you want to avert the issue, please do onething.
Instead of the following line,
noteObj.noteTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)]; // at this place
do as follows
NSString *noteTit = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)];
noteObj.noteTitle = noteTit;
[noteTit release];
Similarly do it for others.

How to get the Directory name/path from an opened handle

On opening a directory via zwopenfile(open directory option), it returns a handle for the directory path. Now I need to get the directory path from the handle. Its my requirement.
I could see an example(please see the code below) where file name can be fetched from file handle. But the below example does not help for directory. Is there any possibilities in fetching directory name from its opened handle.
CHAR* GetFileNameFromHandle(HANDLE hFile)
{
BOOL bSuccess = FALSE;
TCHAR pszFilename[MAX_PATH+1];
HANDLE hFileMap;
// Get the file size.
DWORD dwFileSizeHi = 0;
DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);
if( dwFileSizeLo == 0 && dwFileSizeHi == 0 )
{
printf("Cannot map a file with a length of zero.\n");
return FALSE;
}
// Create a file mapping object.
hFileMap = CreateFileMappingW(hFile,
NULL,
PAGE_READONLY,
0,
1,
NULL);
if (hFileMap)
{
// Create a file mapping to get the file name.
void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
if (pMem)
{
if (GetMappedFileNameW (GetCurrentProcess(),
pMem,
pszFilename,
MAX_PATH))
{
// Translate path with device name to drive letters.
TCHAR szTemp[1024];
szTemp[0] = '\0';
if (GetLogicalDriveStrings(1024-1, szTemp))
{
TCHAR szName[MAX_PATH];
TCHAR szDrive[3] = TEXT(" :");
BOOL bFound = FALSE;
TCHAR* p = szTemp;
do
{
// Copy the drive letter to the template string
*szDrive = *p;
// Look up each device name
if (QueryDosDevice(szDrive, szName, MAX_PATH))
{
UINT uNameLen = _tcslen(szName);
if (uNameLen < MAX_PATH)
{
bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0;
if (bFound && *(pszFilename + uNameLen) == _T('\\'))
{
// Reconstruct pszFilename using szTempFile
// Replace device path with DOS path
TCHAR szTempFile[MAX_PATH];
StringCchPrintf(szTempFile,
MAX_PATH,
TEXT("%s%s"),
szDrive,
pszFilename+uNameLen);
StringCchCopyN(pszFilename, MAX_PATH+1, szTempFile, _tcslen(szTempFile));
}
}
}
// Go to the next NULL character.
while (*p++);
} while (!bFound && *p); // end of string
}
}
bSuccess = TRUE;
UnmapViewOfFile(pMem);
}
CloseHandle(hFileMap);
}
_tprintf(TEXT("File name is %s\n"), pszFilename);
return( pszFilename);
}
NtQueryObject did it.
The example from MSDN, which you posted, gives a 'fully qualified' file name, i.e. with the drive letter and the full path.
With that, it should be easy to get the directory name: just strip off everything after the last \.

Resources