IOS 开发 【objective-c 基础1】

时间:2023-03-08 19:45:26

案例:读取本地硬盘上程序根目录下words.txt文件内容,显示每行的字符数。

//
// main.m
// hello
//
// Created by swack on 15/11/27.
// Copyright © 2015年 swack. All rights reserved.
// #import <Foundation/Foundation.h>
#import <mach-o/dyld.h>
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s:%d\t%s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(...)
#endif int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
char path[512];
unsigned size =512;
_NSGetExecutablePath(path,&size);
char *p=strrchr(path, '/');
*p='\0';
char filename[]="/words.txt";
strcat(path,filename);
FILE *wordFile = fopen(path, "r");
char word[100];
while (fgets(word, 100, wordFile)) {
word[strlen(word)-1]='\0';
NSLog(@"%s is %lu characters long",word,strlen(word));
} }
return 0;
}

调试结果:

main.m:57 asdasd is 6 characters long

main.m:57 asxxx is 5 characters long

main.m:57 awrf is 4 characters long

Program ended with exit code: 0

文本内容:

asdasd
asxxx
awrff

首先说明下头文件,此处用到了

#import <mach-o/dyld.h>

_NSGetExecutablePath

此函数用于获取当前应用程序路径。获取的路径是带文件名的,所以此处用strrchr过滤掉,并加上文件名“words.txt”

下来介绍下这个宏,大家都知道,os x 控制台输出都带有时间戳,此宏主要是自定义输出数据的。
最后说下程序,程序非常的简单明了,基本就是从“words.txt”中一行行的读出文本,并输出。

while (fgets(word, 100, wordFile))

读取一行数据,当eof时返回nil,退出循环。