0

アプリのドキュメント フォルダーにある tt ファイルに文字列を書き込もうとしています。文字列を書き込むことはできますが、別の文字列をファイルに書き込むと、他の文字列が上書きされます。文字列の間に空白行を入れて、多くの場合、この形式のテキストファイルにさらに文字列を書き込むことは可能ですか?

ストリン

…</p>

このコードを使用して文字列をテキスト ファイルに書き込みます。1 つの文字列では機能しますが、複数の文字列では機能しません。

NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/Barcodedata.txt",
                              documentsDirectory];
        //create content - four lines of text
        NSString *content = [NSString stringWithFormat:@"%@",sym.data];
        //save content to the documents directory
        [content writeToFile:fileName
                  atomically:NO
                    encoding:NSStringEncodingConversionAllowLossy
                       error:nil];
4

1 に答える 1

2

コードの実装方法に応じて、これを行う方法がいくつかあります。

1 つの方法は、元の .txt ファイルを NSMutableString オブジェクトにロードし、その新しい行を文字列の末尾に追加して、ファイルを書き直すことです (これは、特に 1000 の後に追加を開始するため、非常に効率的ではありません)ストリング、100 ストリング、50 ストリングなど)

fwriteまたは、低レベル C 関数 " " をappend ビットを設定して使用することもできます。

編集:

コードを見たいので、私の最初の提案でそれを行う方法は次のとおりです。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/Barcodedata.txt", documentsDirectory];
//create content - four lines of text

NSError * error = NULL;
NSStringEncoding encoding;
NSMutableString * content = [[NSMutableString alloc] initWithContentsOfFile: fileName usedEncoding: &encoding error: &error];
if(content == NULL)
{
    // if the file doesn't exist yet, we create a mutable string
    content = [[NSMutableString alloc] init];
}

if(content)
{
    [content appendFormat: @"%@", sym.data];

    //save content to the documents directory
    BOOL success = [content writeToFile:fileName
                            atomically:NO
                              encoding:NSStringEncodingConversionAllowLossy
                                 error:&error];

    if(success == NO)
    {
        NSLog( @"couldn't write out file to %@, error is %@", fileName, [error localizedDescription]);
    }
}
于 2013-04-06T09:51:50.127 に答える