문제

방금 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의 파일 경로가 필요한 경우 쉽게 얻을 수있는 방법은 파일을 명령을 입력하는 터미널 .App 창으로 드래그하는 것입니다. 짜잔!

다른 팁

데스크탑으로가는 길은입니다 /Users/[username]/Desktop/

~/Desktop/ 이를 나타내는 사용자 공유 방법입니다. ~ 현재 사용자 홈 디렉토리를 나타냅니다. 같은 방법을 사용하여 확장해야합니다 stringByExpandingTildeInPath

C#을 사용하는 것에 대해 잘 모르겠습니다 (Mac OS X에서는 사용해 본 적이 없음). 대상 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"]

내가 말했듯이, 두 가지 모두 객관적인 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

터미널이 자동으로 확장됩니다 ~/ 틸다 경로

가까이 ...

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

... 여기서 {volume}은 하드 드라이브의 이름입니다. 다음을 사용해 볼 수도 있습니다.

~/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