Objective C Adding content to a file - objective-c

I need to write several line to a file. How can I move to the next line so that the file content is not overwritten each time? I am using a for loop with the following code in it
[anNSString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
The NSString. anNSString is reinitialized during each loop. SO i need to keep adding to the file path each during each loop.
Thanks

I feel like the accepted answer is not correct since it didn't answer the original question. To solve the original question you should use an NSOutputStream it makes appending content to an existing file an easy task:
NSString *myString = #"Text to append!"; // don't forget to add linebreaks if needed (\r\n)
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
[stream open];
NSData *strData = [myString dataUsingEncoding:NSUTF8StringEncoding];
[stream write:(uint8_t *)[strData bytes] maxLength:[strData length]];
[stream close];

You just write it out all at once, rather than attempting to write it incrementally. -[NSString writeToFile:atomically:encoding:error] will just overwrite the file each time - it does not append.
Here's an illustration:
NSMutableString * str = [NSMutableString new];
// > anNSString is reinitialized during each loop.
for ( expr ) {
NSString * anNSString = ...;
// > SO i need to keep adding to the file path each during each loop.
[str appendString:anNSString];
}
NSError * outError(0);
BOOL success = [str writeToFile:path
atomically:YES
encoding:NSUTF8StringEncoding
error:&outError];
[str release];
...

If you need to write to a new line each time, start with what is in #justin's answer, but add [str appendString:#"\r\n"]; wherever you need new lines.
NSMutableString * str = [NSMutableString new];
// > anNSString is reinitialized during each loop.
for ( expr ) {
NSString * anNSString = ...;
// > SO i need to keep adding to the file path each during each loop.
[str appendString:anNSString];
[str appendString:#"\r\n"]; //****** THIS IS THE NEW LINE ******
}
NSError * outError(0);
BOOL success = [str writeToFile:path
atomically:YES
encoding:NSUTF8StringEncoding
error:&outError];
[str release];
...
With this code, each anNSString will be on it's own line in the text file.

Related

Error writing to long value to file Objective-C

I'm trying to create 9 text files on my Desktop which are named by variable i in the for loop. Inside each text file I want to write a long value determined by my bigInt function. The long value must then be written in the file 1000 times before moving on to the next text file. But I keep getting the error: Incompatible pointer types sending 'NSString*' to parameter of type 'NSData*'
My Function:
long bigInt(int i){
long big = 99*(i*99);
long evenBigger = big*(big*(big*big));
return evenBigger;
}
My main method:
long use;
int x = 0;
for (int i = 1; i<10; i++) {
while (x < 1000) {
use = bigInt(i);
//[NSString stringWithFormat:#"%ld", use];
//NSString *content = #"Text to write to file";
NSString *path = [NSString stringWithFormat: # "/Users/ou_snaaksie/Desktop/%i.txt", i];
//NSData *fileContents = [use dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:path contents:[NSString stringWithFormat:#"%ld", use] attributes:nil];
x++;
}
}
I think you need to pass NSData instead of NSString object to contents in createFileAtPath:contents:attributes: method or you can do something like below:
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
}
[[string dataUsingEncoding:NSUTF8StringEncoding] writeToFile:path atomically:YES];
You are passing a string as contents when it requires NSData. You have to convert the string to NSData. Try this in the body of your while loop:
use = bigInt(i);
NSString* str = [NSString stringWithFormat:#"%ld", use];
NSData* data_contents = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *path = [NSString stringWithFormat: # "/tmp/%i.txt", i];
[data_contents writeToFile:path atomically:YES];
x++;

ObjectiveC - Read from console string with multiple lines (Breaks\newLine)

Is there a way in objectiveC to read a string with multiple lines from user input in the console?
I'm making a simple console app in Xcode, which i want people to be able to paste SQL queries which may be in few lines.
Currently i'm using:
char strIn[512];
NSMutableString* str;
scanf("%[^\n]", strIn);
str = [NSString stringWithUTF8String:strIn];
NSLog(#"\n%#",str);
But this only gets the first line.
Remember - this is not about reading from file, but only from the console.
thanks.
The following code should help you to get started. It reads from standard input and collects the input lines in the inputString variable, until a semi-colon is found.
NSFileHandle *inputFile = [NSFileHandle fileHandleWithStandardInput];
NSMutableString *inputString = [NSMutableString string];
do {
// Read from stdin, check for EOF:
NSData *data = [inputFile availableData];
if ([data length] == 0) {
NSLog(#"EOF");
break;
}
// Convert to NSString, replace newlines by spaces, append to current input:
NSMutableString *tmp = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[tmp replaceOccurrencesOfString:#"\n" withString:#" " options:0 range:NSMakeRange(0, [tmp length])];
[inputString appendString:tmp];
// Check for semi-colon:
} while ([inputString rangeOfString:#";"].location == NSNotFound);
NSLog(#"input=%#", inputString);
(Note that this sample code simple checks for a semi-colon somewhere in the input. It does not check if the semi-colon is e.g. embedded in a string.)

How to save an array with float values into a text file that is readable by Mac?

I want to save float values stored in an array into a text file and read the file directly on Mac. This is how I create the array:
dataArray = [[NSMutableArray alloc] init];
NSNumber *numObj = [NSNumber numberWithFloat:3.14];
[dataArray insertObject:numObj atIndex:0];
NSNumber *numObj = [NSNumber numberWithFloat:2.3];
[dataArray insertObject:numObj atIndex:1];
...
This is how I save the array:
NSData *savedData = [NSKeyedArchiver archivedDataWithRootObject:dataArray];
NSString *filePath = #"/Users/smith/Desktop/dataArray.txt";
[savedData writeToFile:filePath options:NSDataWritingAtomic error:nil];
When I open the file, the contents are just garbled letters. Instead, I want to make it something like this:
3.14
2.3
1.4
...
the program you've written saves the object representation as an array of NSNumbers, while
the result you want/expect is a text file separated by newlines.
to save those float values into a text file of that format, you could to this:
...
NSMutableString * string = [NSMutableString new];
[string appendFormat:#"%f\n", 3.14];
[string appendFormat:#"%f\n", 2.3];
NSError * error = nil;
BOOL written = [string writeToURL:url atomically:YES encoding:someEncoding error:&error];
...
You can use componentsJoinedByString: to make an in-memory representation first, and then write that representation into a file, like this:
NSString *fileRep = [dataArray componentsJoinedByString:#"\n"];
NSString *filePath = #"/Users/smith/Desktop/dataArray.txt";
[fileRep writeToFile:filePath options:NSDataWritingAtomic error:nil];
This assumes that the number of items is relatively small, because the string representation is created entirely in memory.
Reading back is not as nice as writing out, though: you start by reading back a string, theb split it to components using [fileRep componentsSeparatedByString:#"\n"], and then go through components in a loop or with a block, adding [NSNumber numberWithDouble:[element doubleValue]] for each element of your split.
You probably want to create an XML plist from it to make it human-readable:
[dataArray writeToFile:filePath atomically:YES];
This creates a property list, which is human-readable XML (except if the file already exists AND it's a binary plist, in this case the new plist will also be binary).

Reading a File Character by character in iOS

Basically i have a concern, which needs to be solved using Objective C alone. (i have tried with C)
Is there any appropriate way in objective C to read character by character (till EOF) from a file, which is placed in document directory. So, I will append a escape character before all inverted comma's in a file and A special character (say /) before each line.
Replace
(type == "Project")
with
/(doc.type == \"Project\")
if u feel my approach is not correct is there any other method to accomplish this task in an efficient way?
Get all the lines from your file, make your changes such as replacing characters or adding more text, and then save the file.
NSString *objPath = [[NSBundle mainBundle] pathForResource:#"textfile" ofType:#"txt"];
NSData *objData = [[NSData alloc] initWithContentsOfFile:objPath];
NSString *objString = [[NSString alloc] initWithData:objData encoding:NSUTF8StringEncoding];
NSMutableArray *lines = [NSMutableArray arrayWithArray:[objString componentsSeparatedByString:#"\n"]];
for (int i = 0; i < lines.count; i++) {
NSString *oneLine = [lines objectAtIndex:i];
if (oneLine.length < 2) {
continue;
}
oneLine = [NSString stringWithFormat:#"/%#", oneLine];
oneLine = [oneLine stringByReplacingOccurrencesOfString:#"`" withString:#"\`"];
[lines replaceObjectAtIndex:i withObject:oneLine];
}
NSString *finalString = [lines componentsJoinedByString:#"\n"];
//save the file
You can use NSFileHandle and invoke readDataAtLength: with a value of 1.

Convert NSData bytes to NSString?

I'm trying to use the BEncoding ObjC class to decode a .torrent file.
NSData *rawdata = [NSData dataWithContentsOfFile:#"/path/to/the.torrent"];
NSData *torrent = [BEncoding objectFromEncodedData:rawdata];
When I NSLog torrent I get the following:
{
announce = <68747470 3a2f2f74 6f727265 6e742e75 62756e74 752e636f 6d3a3639 36392f61 6e6e6f75 6e6365>;
comment = <5562756e 74752043 44207265 6c656173 65732e75 62756e74 752e636f 6d>;
"creation date" = 1225365524;
info = {
length = 732766208;
name = <7562756e 74752d38 2e31302d 6465736b 746f702d 69333836 2e69736f>;
"piece length" = 524288;
....
How do I convert the name into a NSString? I have tried..
NSData *info = [torrent valueForKey:#"info"];
NSData *name = [info valueForKey:#"name"];
unsigned char aBuffer[[name length]];
[name getBytes:aBuffer length:[name length]];
NSLog(#"File name: %s", aBuffer);
..which retrives the data, but seems to have additional unicode rubbish after it:
File name: ubuntu-8.10-desktop-i386.iso)
I have also tried (from here)..
NSString *secondtry = [NSString stringWithCharacters:[name bytes] length:[name length] / sizeof(unichar)];
..but this seems to return a bunch of random characters:
扵湵畴㠭ㄮⴰ敤歳潴⵰㍩㘸椮潳
The fact the first way (as mentioned in the Apple documentation) returns most of the data correctly, with some additional bytes makes me think it might be an error in the BEncoding library.. but my lack of knowledge about ObjC is more likely to be at fault..
That's an important point that should be re-emphasized I think. It turns out that,
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
is not the same as,
NSString *content = [[NSString alloc] initWithBytes:[responseData bytes]
length:[responseData length] encoding: NSUTF8StringEncoding];
the first expects a NULL terminated byte string, the second doesn't. In the above two cases content will be NULL in the first example if the byte string isn't correctly terminated.
How about
NSString *content = [[[NSString alloc] initWithData:myData
encoding:NSUTF8StringEncoding] autorelease];
NSData *torrent = [BEncoding objectFromEncodedData:rawdata];
When I NSLog torrent I get the following:
{
⋮
}
That would be an NSDictionary, then, not an NSData.
unsigned char aBuffer[[name length]];
[name getBytes:aBuffer length:[name length]];
NSLog(#"File name: %s", aBuffer);
..which retrives the data, but seems to have additional unicode rubbish after it:
File name: ubuntu-8.10-desktop-i386.iso)
No, it retrieved the filename just fine; you simply printed it incorrectly. %s takes a C string, which is null-terminated; the bytes of a data object are not null-terminated (they are just bytes, not necessarily characters in any encoding, and 0—which is null as a character—is a perfectly valid byte). You would have to allocate one more character, and set the last one in the array to 0:
size_t length = [name length] + 1;
unsigned char aBuffer[length];
[name getBytes:aBuffer length:length];
aBuffer[length - 1] = 0;
NSLog(#"File name: %s", aBuffer);
But null-terminating the data in an NSData object is wrong (except when you really do need a C string). I'll get to the right way in a moment.
I have also tried […]..
NSString *secondtry = [NSString stringWithCharacters:[name bytes] length:[name length] / sizeof(unichar)];
..but this seems to return random Chinese characters:
扵湵畴㠭ㄮⴰ敤歳潴⵰㍩㘸椮潳
That's because your bytes are UTF-8, which encodes one character in (usually) one byte.
unichar is, and stringWithCharacters:length: accepts, UTF-16. In that encoding, one character is (usually) two bytes. (Hence the division by sizeof(unichar): it divides the number of bytes by 2 to get the number of characters.)
So you said “here's some UTF-16 data”, and it went and made characters from every two bytes; each pair of bytes was supposed to be two characters, not one, so you got garbage (which turned out to be mostly CJK ideographs).
You answered your own question pretty well, except that stringWithUTF8String: is simpler than stringWithCString:encoding: for UTF-8-encoded strings.
However, when you have the length (as you do when you have an NSData), it is even easier—and more proper—to use initWithBytes:length:encoding:. It's easier because it does not require null-terminated data; it simply uses the length you already have. (Don't forget to release or autorelease it.)
A nice quick and dirty approach is to use NSString's stringWithFormat initializer to help you out. One of the less-often used features of string formatting is the ability to specify a mximum string length when outputting a string. Using this handy feature allows you to convert NSData into a string pretty easily:
NSData *myData = [self getDataFromSomewhere];
NSString *string = [NSString stringWithFormat:#"%.*s", [myData length], [myData bytes]];
If you want to output it to the log, it can be even easier:
NSLog(#"my Data: %.*s", [myData length], [myData bytes]);
Aha, the NSString method stringWithCString works correctly:
With the bencoding.h/.m files added to your project, the complete .m file:
#import <Foundation/Foundation.h>
#import "BEncoding.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Read raw file, and de-bencode
NSData *rawdata = [NSData dataWithContentsOfFile:#"/path/to/a.torrent"];
NSData *torrent = [BEncoding objectFromEncodedData:rawdata];
// Get the file name
NSData *infoData = [torrent valueForKey:#"info"];
NSData *nameData = [infoData valueForKey:#"name"];
NSString *filename = [NSString stringWithCString:[nameData bytes] encoding:NSUTF8StringEncoding];
NSLog(#"%#", filename);
[pool drain];
return 0;
}
..and the output:
ubuntu-8.10-desktop-i386.iso
In cases where I don't have control over the data being transformed into a string, such as reading from the network, I prefer to use NSString -initWithBytes:length:encoding: so that I'm not dependent upon having a NULL terminated string in order to get defined results. Note that Apple's documentation says if cString is not a NULL terminated string, that the results are undefined.
Use a category on NSData:
NSData+NSString.h
#interface NSData (NSString)
- (NSString *)toString;
#end
NSData+NSString.m
#import "NSData+NSString.h"
#implementation NSData (NSString)
- (NSString *)toString
{
Byte *dataPointer = (Byte *)[self bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:0];
NSUInteger index;
for (index = 0; index < [self length]; index++)
{
[result appendFormat:#"0x%02x,", dataPointer[index]];
}
return result;
}
#end
Then just NSLog(#"Data is %#", [nsData toString])"
You can try this. Fine with me.
DLog(#"responeData: %#", [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSASCIIStringEncoding] autorelease]);
Sometimes you need to create Base64 encoded string from NSData. For instance, when you create a e-mail MIME. In this case use the following:
#import "NSData+Base64.h"
NSString *string = [data base64EncodedString];
This will work.
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];