Xcodeの&渡すコマンドライン引数
-
19-09-2019 - |
質問
私はC&Xcodeので仕事を始めたと私はほとんど困難に遭遇してきます。
私がやりたいことすべては、コマンドラインからファイルを読み込むと、端末に出力が表示されます。
私はマックを使っていて、ファイルがデスクトップ上にあるので、パスが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
解決
、それを得るための簡単な方法は、ちょうどあなたがコマンドを入力しているTerminal.appウィンドウにファイルをドラッグすることです。出来上がり!
他のヒント
デスクトップへのパスが/Users/[username]/Desktop/
である
~/Desktop/
がこれを表すのユーザーに依存しない方法で、~
は、現在のユーザーのホームディレクトリを表します。それは<のhref = "http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSStringのような方法を使用して拡張する必要があります/ stringByExpandingTildeInPath」のrel = "nofollowをnoreferrer"> stringByExpandingTildeInPath
の
(私は、Mac OS X上でそれを使用したことがありません)C#を使用について確認が、Objective-Cの/ココアではない、あなたはどうなる..
// 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#2に変換するのは難しいことではないはずです。
両方 <時間>あなたは正しく作品を掲載コード:
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");
あなたは、引数としてファイル名を渡すことでに実行している問題は、ファイルが存在する場所に現在の作業ディレクトリを設定する必要があるということです。