zoukankan      html  css  js  c++  java
  • IOS 开发 【objective-c 基础1】

    案例:读取本地硬盘上程序根目录下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	%s
    ",[[[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='';
            char filename[]="/words.txt";
            strcat(path,filename);
            FILE *wordFile = fopen(path, "r");
            char word[100];
            while (fgets(word, 100, wordFile)) {
                word[strlen(word)-1]='';
                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,退出循环。

  • 相关阅读:
    How to use django with mod_wsgi ¶
    How to install Apache2 (CentOS 5.4)
    Review Board
    代理
    你的第一个Javascript服务器端程序(一)
    程序员的十层楼(6~7层)
    用你自己的插件扩展jQuery(Extend jQuery with Your Very Own Plugin)
    程序员的十层楼(1~5层)
    C#到Java byte类型冲突的解决
    Hadoop出现allocate memory错误的解决
  • 原文地址:https://www.cnblogs.com/swack/p/5006937.html
Copyright © 2011-2022 走看看