簡體   English   中英

從/ .txt文件讀取和寫入整數

[英]Read and write an integer to/from a .txt file

如何在文本文件中讀取和寫入整數,是否可以讀取或寫入多行,即處理多個整數?

謝謝。

這當然是可能的; 它只取決於文本文件的確切格式。
閱讀文本文件的內容很簡單:

// If you want to handle an error, don't pass NULL to the following code, but rather an NSError pointer.
NSString *contents = [NSString stringWithContentsOfFile:@"/path/to/file" encoding:NSUTF8StringEncoding error:NULL];

這會創建一個包含整個文件的自動釋放字符串。 如果包含的所有文件都是整數,那么您可以這樣寫:

NSInteger integer = [contents integerValue];

如果文件被分成多行(每行包含一個整數),則必須將其拆分:

NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *line in lines) {
    NSInteger currentInteger = [line integerValue];
    // Do something with the integer.
}

總的來說,它非常簡單。


寫回文件同樣容易。 一旦你將你想要的東西操作回一個字符串,你就可以使用它:

NSString *newContents = ...; // New string.
[newContents writeToFile:@"/path/to/file" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

您可以使用它來寫入字符串。 當然,您可以使用設置。 atomically設置為YES會導致它首先寫入測試文件,驗證它,然后將其復制以替換舊文件(這可確保如果發生某些故障,您將不會得到損壞的文件)。 如果需要,可以使用不同的編碼(雖然強烈建議使用NSUTF8StringEncoding ),如果要捕獲錯誤(本質上應該是這樣),可以將NSError的引用傳遞給方法。 它看起來像這樣:

NSError *error = nil;
[newContents writeToFile:@"someFile.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
    // Some error has occurred. Handle it.
}

有關進一步閱讀,請參閱NSString類參考

如果必須寫入多行,請在構建newContents字符串時使用\\r\\n指定要放置換行符的位置。

NSMutableString *newContents = [[NSMutableString alloc] init];

for (/* loop conditions here */)
{
    NSString *lineString = //...do stuff to put important info for this line...
    [newContents appendString:lineString];
    [newContents appendString:@"\r\n"];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM