`
zl4393753
  • 浏览: 340228 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Working with Directories in Objective-C

 
阅读更多
Working with Directories in Objective-C

original address: http://www.techotopia.com/index.php/Working_with_Directories_in_Objective-C

A key element of gaining proficiency in any programming language involves the ability to work with files and file systems. The level of difficulty in working with files varies from very easy to hard, depending on the programming language concerned. The C programming language, on which Objective-C is based, tended to make file handling a little hard relative to the standards of today's programmer friendly object oriented languages. The good news for Objective-C developers is that the Foundation Framework includes a number of classes designed specifically to make the task of working with files and directories as straightforward as possible.
In this chapter we will look at these classes and provide examples of how use them to perform some basic directory operations from within an Objective-C program. In Working with Files in Objective-C we will take a close look at working with files using these classes.

The Objective-C NSFileManager, NSFileHandle and NSData Classes
The Foundation Framework provides three classes that are indispensable when it comes to working with files and directories:
NSFileManager - The NSFileManager class can be used to perform basic file and directory operations such as creating, moving, reading and writing files and reading and setting file attributes. In addition, this class provides methods for, amongst other tasks, identifying the current working directory, changing to a new directory, creating directories and listing the contents of a directory.
NSFileHandle - The NSFileHandle class is provided for performing lower level operations on files, such as seeking to a specific position in a file and reading and writing a file's contents by a specified number of byte chunks and appending data to an existing file.
NSData - The NSData class provides a useful storage buffer into which the contents of a file may be read, or from which data may be written to a file.
Understanding Pathnames in Objective-C

When using the above classes, pathnames are defined using the UNIX convention. As such each component of a path is separated by a forward slash (/). Paths that do not begin with a slash are interpreted to be relative to a current working directory. For example, if the current working directory is /home/objc and the path name is myapp/example.m then the file is considered to have a full pathname of /home/objc/myapp/example.m.
In addition, the home directory of the current user can be represented using the tilde (~) character. For example the pathname ~/example.m references a file named example.m located in the home directory of the current user. The home directory of another user may be referenced by prefixing the user name with a ~. For example, ~john/demo.m references a file located in the home directory of a user named john.
Obtaining a Reference to the Default NSFileManager Object

The NSFileManager class contains a class method named defaultManager that is used to obtain a reference to the application’s default file manager instance:
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];


In the above example we have declared a variable named filemgr to point to an object of type NSFileManager, and then requested a pointer to the application’s file manager and assigned it to the variable. Having obtained the object reference we can begin to use it to work with files and directories.
Identifying the Current Working Directory

The current working directory may be identified using the currentDirectoryPath instance method of our NSFileManager object. The current path is returned from the method in the form of an NSString object:
NSFileManager *filemgr;
NSString *currentpath;

filemgr = [NSFileManager defaultManager];

currentpath = [filemgr currentDirectoryPath];

NSLog (@"Current directory is %@", currentpath);


Changing to a Different Directory

The current working directory of a running Objective-C program can be changed with a call to the changeCurrentDirectoryPath method. The destination directory path is passed as an argument to the instance method in the form of an NSString object. Note that this method returns a boolean YES or NO result to indicate if the requested directory change was successful for not:
NSFileManager *filemgr;
NSString *currentpath;

filemgr = [NSFileManager defaultManager];

currentpath = [filemgr currentDirectoryPath];

NSLog (@"Current directory is %@", currentpath);

if ([filemgr changeCurrentDirectoryPath: @"/temp/mydir"] == NO)
        NSLog (@"Cannot change directory.");

currentpath = [filemgr currentDirectoryPath];

NSLog (@"Current directory is %@", currentpath);


Creating a New Directory

A new directory is created using the createDirectoryAtURL instance method, this time passing through the through the pathname of the new directory as an argument in the form of an NSURL object. This method also takes additional arguments in the form of a set of attributes for the new directory and a Boolean value indicating whether or not intermediate directories should be created if they do not already exist. Specifying nil will use the default attributes:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];
NSURL *newDir = [NSURL fileURLWithPath:@"/tmp/mynewdir"];
[filemgr createDirectoryAtURL: newDir withIntermediateDirectories:YES attributes: nil error:nil];


The createDirectoryAtURL method returns a Boolean result indicating the success or otherwise of the operation.
Deleting a Directory

An existing directory may be removed from the file system using the removeItemAtPath method, passing though the path of the directory to be removed as an argument:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

[filemgr removeItemAtPath: @"/tmp/mynewdir" handler: nil];


Renaming or Moving a File or Directory

An existing file or directory may be moved (also known as renaming) using the moveItemAtURL method. This method takes the source and destination pathnames as arguments in the form of NSURL objects and requires that the destination path not already exist. If the target exists, a boolean NO result is returned by the method to indicate failure of the operation:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

NSURL *oldDir = [NSURL fileURLWithPath:@"/tmp/mynewdir"];
NSURL *newDir = [NSURL fileURLWithPath:@"/tmp/mynewdir2"];

[filemgr moveItemAtURL: oldDir toURL: newDir error: nil];


Getting a Directory File Listing

A listing of the files contained within a specified directory can be obtained using the contentsOfDirectoryAtPath method. This method takes the directory pathname as an argument and returns an NSArray object containing the names of the files and sub-directories in that directory:

NSFileManager *filemgr;
NSString *currentpath;
NSArray *filelist;
int count;
int i;

filemgr = [NSFileManager defaultManager];

filelist = [filemgr contentsOfDirectoryAtPath: @"/tmp" error: nil];

count = [filelist count];

for (i = 0; i < count; i++)
        NSLog (@"%@", [filelist objectAtIndex: i]);


When executed as part of a program, the above code excerpt will display a listing of all the files located in the /tmp directory.
Getting the Attributes of a File or Directory

The attributes of a file or directory can be obtained using the attributesOfItemAtPath method. This takes as arguments the path of the directory and an optional NSError object into which information about any errors will be placed (may be specified as NULL if this information is not required). The results are returned in the form of an NSDictionary dictionary object (for details of working with dictionary objects refer to Objective-C Dictionary Objects). The keys for this dictionary are as follows:

 
NSFileType
NSFileTypeDirectory
NSFileTypeRegular
NSFileTypeSymbolicLink
NSFileTypeSocket
NSFileTypeCharacterSpecial
NSFileTypeBlockSpecial
NSFileTypeUnknown
NSFileSize
NSFileModificationDate
NSFileReferenceCount
NSFileDeviceIdentifier
NSFileOwnerAccountName
NSFileGroupOwnerAccountName
NSFilePosixPermissions
NSFileSystemNumber
NSFileSystemFileNumber
NSFileExtensionHidden
NSFileHFSCreatorCode
NSFileHFSTypeCode
NSFileImmutable
NSFileAppendOnly
NSFileCreationDate
NSFileOwnerAccountID
NSFileGroupOwnerAccountID

For example, we can extract the creation date, file type and POSIX permissions for the /tmp directory using the following code excerpt:

NSFileManager *filemgr;
NSDictionary *attribs;

filemgr = [NSFileManager defaultManager];

attribs = [filemgr attributesOfItemAtPath: @"/tmp" error: NULL];

NSLog (@"Created on %@", [attribs objectForKey: NSFileCreationDate]);
NSLog (@"File type %@", [attribs objectForKey: NSFileType]);
NSLog (@"POSIX Permissions %@", [attribs objectForKey: NSFilePosixPermissions]);


When executed on a Mac OS X system, we can expect to see the following output (note that /tmp on a Mac OS X system is a symbolic link to private/tmp):
Created on 2009-01-14 07:34:32 -0500
File type NSFileTypeSymbolicLink
POSIX Permissions 493
分享到:
评论

相关推荐

    Win10利用CodeBlocks搭建Objective-C开发环境(一).pdf

    随着iOS应用的日益流行,越来越多的开发者希望能够快速上手Objective-C语言。然而,并非所有人都能拥有苹果设备来直接进行开发。因此,在Windows平台上搭建Objective-C开发环境成为了一种可行的选择。本文将详细介绍...

    Windows下的Objective-C集成开发环境的搭建

    【搭建Objective-C集成开发环境】 Objective-C是一种主要应用于苹果平台的编程语言,尤其在iOS和macOS应用开发中占据核心地位。尽管它主要与苹果的Xcode IDE紧密关联,但在Windows环境下,我们同样可以通过配置其他...

    Objective-C for Absolute Beginners: iPhone and Mac Programming Made Easy

    - **Creating Cool Apps:** With a solid foundation in Objective-C and familiarity with Cocoa and Cocoa Touch, you'll be ready to create your own applications. The book provides practical examples and ...

    C语言目录递归经典代码Recurse-Directories-in-C

    在`Recurse-Directories-in-C-master`这个项目中,可能包含了完整的目录递归示例代码,包括错误处理和更复杂的逻辑,比如排除特定文件类型或者处理软链接。这样的代码可以帮助你理解和学习如何在实际项目中应用目录...

    Windows XP 系统下创建 Objective-C 集成开发环境

    ### Windows XP 系统下创建 Objective-C 集成开发环境 #### 概述 本文旨在详细介绍如何在 Windows XP 操作系统中搭建一套基于 GNUstep 和 CodeBlocks 的 Objective-C 集成开发环境(IDE)。该环境对于希望在 ...

    PyPI 官网下载 | clean_directories-1.1.0-py3-none-any.whl

    **PyPI 官网下载 | clean_directories-1.1.0-py3-none-any.whl** `clean_directories-1.1.0-py3-none-any.whl` 是一个在Python Package Index (PyPI) 上发布的软件包,用于管理项目中的目录。PyPI是Python开发者...

    PyPI 官网下载 | ldap3_directories-0.2.4-py3-none-any.whl

    资源来自pypi官网。 资源全名:ldap3_directories-0.2.4-py3-none-any.whl

    Python库 | ldap3_directories-0.2.4-py3-none-any.whl

    **Python库ldap3_directories-0.2.4-py3-none-any.whl详解** `ldap3_directories` 是一个Python库,专为处理 Lightweight Directory Access Protocol (LDAP) 目录服务而设计。这个库的版本是0.2.4,它支持Python 3....

    Windows下搭建Objective C开发环境

    在Windows环境下搭建Objective-C开发环境是一项相对复杂的工作,因为Objective-C主要是与苹果的 macOS 和 iOS 平台紧密关联,而这些平台通常使用Xcode作为主要的开发工具。然而,通过一些开源工具,我们可以在...

    h10638-tt-isilon-for-home-directories-and-fileshares

    ### Isilon横向扩展NAS在家庭目录和文件共享中的应用 #### 消除NAS孤岛 在现代企业环境中,网络附加存储(Network Attached Storage, NAS)常常成为数据存储的关键组成部分。随着组织规模的扩大和技术的进步,传统的...

    codeblock-object-c开发环境搭建

    ### Objective-C 开发环境搭建详解:使用 Codeblocks #### 一、概述 Objective-C 是一种通用、面向对象的编程语言,最初由苹果公司用于 macOS 和 iOS 操作系统的开发。为了能够在计算机上进行 Objective-C 的学习...

    《C语言的科学和艺术》和《程序设计抽象思想-C语言描述》中要用的库(包括源代码和使用教程)

    将CS106Inc复制到\Microsoft Visual Studio\VC98\Include下,并设置VC的Include directories(在Tools/Options/Directories)加上CS106Inc完整路径. 再复制CS106lib.lib到\Microsoft Visual Studio\VC98\lib目录下。 ...

    svn: This client is too old to work with

    项目中使用的是1.4.7,作为eclipse的插件装的;后来又在机子上装了个TortoiseSVN 1.6.5。... --skip-unknown-format : skip directories with unknown working copy format and continue the update

    将文件和文件夹分开的lf

    以前常常在找让ls单独列出文件或文件夹的方法,基本上都是通过一些shell处理,不过得到的结果一般都没有格式。... -c --count count there are how much files and directories. -h --help show this.

    arm-linux-gcc交叉编译器 4.3.2 part2

    Using built-in specs. Target: arm-none-linux-gnueabi Configured with: /scratch/julian/lite-respin/linux/src/gcc-4.3/configure --build=i686-pc-linux-gnu --host=i686-pc-linux-gnu --target=arm-none-linux...

    Directories-And-Files

    在IT行业中,目录(Directories)和文件(Files)是计算机操作系统中最基本的组织单元,用于存储和管理数据。本主题将深入探讨这两个概念,以及它们在CSS(Cascading Style Sheets)中的应用。 目录,也被称为...

    cli-essentials-bash-files-and-directories-chicago-web-120919

    在Bash中浏览文件和目录 学习目标 用ls shell中的目录文件 使用mv移动或重命名文件和目录 使用cp复制文件 touch创建空文件 用mkdir新建目录 用rm删除文件 介绍 在上一课中,我们学习了如何“导航”文件系统的目录...

    cli-essentials-bash-files-and-directories-den-web-071519

    在Bash中浏览文件和目录 学习目标 用ls shell中的目录文件 使用mv移动或重命名文件和目录 使用cp复制文件 touch创建空文件 用mkdir新建目录 用rm删除文件 介绍 在上一课中,我们学习了如何“导航”文件系统的目录...

    cli-essentials-bash-files-and-directories-sfo-web-033020

    在Bash中浏览文件和目录 学习目标 用ls shell中的目录文件 使用mv移动或重命名文件和目录 使用cp复制文件 touch创建空文件 用mkdir新建目录 用rm删除文件 介绍 在上一课中,我们学习了如何“导航”文件系统的目录...

Global site tag (gtag.js) - Google Analytics