我刚刚开始使用 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
有帮助吗?

解决方案

如果您需要的路径,在OS X中,一个文件一个简单的方法来获得它只是拖动文件到您键入的命令下的Terminal.app窗口。瞧!

其他提示

桌面的路径是 /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 语言,但转换为 C# 应该不难,假设您可以访问 Cocoa 库。


您发布的代码工作正常:

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

您的终端会自动扩展 ~/ 蒂尔达路径

关闭......这是

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

...其中{音量}是您的硬盘驱动器的名称。您也可以尝试使用:

~/Desktop/words.txt

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

(注 - 这似乎是一个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");

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top