Xcode&传递命令行参数

时间:2009-08-19 23:54:04

标签: c macos command-line-arguments

我刚开始使用C& Xcode和我遇到了一些困难。

我想要做的就是从命令行读取文件并查看终端中的输出。 我认为我的问题在于我想要阅读的文件的路径。我使用的是Mac,文件在我的桌面上,所以路径应该是Users/myName/Desktop/words.txt。这是对的吗?

这是我的代码:

#import <Foundation/Foundation.h>

int main (int argc, const char* argv[]){

    if(argc == 1){
        NSLog(@" you must pass at least one arguement");
        return 1;
    }
    NSLog(@"russ");
    FILE*  wordFile = fopen(argv[1] , "r");
    char word[100];

    while (fgets(word,100,wordFile)) {

        NSLog(@" %s is %d chars long", word,strlen(word));

    }

    fclose(wordFile);
    return 0;

}//main

4 个答案:

答案 0 :(得分:2)

桌面路径为/Users/[username]/Desktop/

~/Desktop/是一种与用户无关的表示方式,~表示当前用户的主目录。必须使用stringByExpandingTildeInPath

等方法进行扩展

不确定使用C#(我从未在Mac OS X上使用它),但在Objective-C / Cocoa中,你会这样做..

// Get array with first index being path to desktop
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);

// Get the first element
NSString *desktopPath = [paths objectAtIndex:0];

// Append words.txt to path
NSString *theFilePath = [desktopPath stringByAppendingPathComponent:@"words.txt"];

NSLog(@"%@", theFilePath);

这是获取桌面路径最强大的方法,因为用户可以在技术上将其桌面文件夹移动到其他位置(尽管这不太可能)。另一个有效选项是使用NSString方法stringByExpandingTildeInPath

NSString *desktop = [@"~/Desktop" stringByExpandingTildeInPath];
NSString *theFile = [desktop stringByAppendingPathComponent:@"words.txt"]

正如我所说,这两个都在Objective-C中,但是如果你可以使用Cocoa库,那么转换为C#应该不难。


您发布的代码正常运行:

dbr:.../build/Debug $ ./yourcode ~/Desktop/words.txt 
yourcode[2106:903] russ
yourcode[2106:903]  this is words.txt is 17 chars long

您的终端会自动展开~/ tilda路径

答案 1 :(得分:2)

如果您需要OS X中文件的路径,获取它的简单方法是将文件拖到您正在键入命令的Terminal.app窗口中。瞧!

答案 2 :(得分:0)

关闭......它是

/{Volume}/Users/myName/Desktop/words.txt

...其中{Volume}是硬盘的名称。您也可以尝试使用:

~/Desktop/words.txt

...其中~被理解为“您的主目录”,但这可能无法正确解析。

答案 3 :(得分:0)

(注意 - 这似乎是一个C问题,而不是C#问题)

实际上,您可以这样做:

/Users/myName/Desktop/words.txt

您不必提供卷的路径。

但是,要获得C中的完整路径,您可以执行以下操作:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *home, *fullPath;

home = getenv("HOME");

fullPath = strcat(home, "/Desktop/words.txt");

将文件名作为参数传递时遇到的问题是您需要将当前工作目录设置为文件所在的位置。