私はこのファイルの頭や尾を作ることができません。私の作業ディレクトリにはinput1.txt
というファイルがありますが、fopen()
です。fopen()はNULLを返します。現在のディレクトリにファイルがあります。
私のディレクトリ構造(Xcodeの):
メイン():
const char* fileName = "input1.txt";
if (argc > 1)
{
fileName = argv[1];
}
printf("Opening file: %s\n", fileName);
clock_t timer = clock();
HashMap* map = hashMapNew(10);
// --- Concordance code begins here ---
// Be sure to free the word after you are done with it here.
FILE *in;
if ((in = fopen(fileName, "r")) == NULL) {
printf ("Can’t open %s for reading. %s\n", fileName, strerror(errno));
}
char* w = nextWord(in);
printf("%s",w);
nextWord():
char* nextWord(FILE* file)
{
int maxLength = 16;
int length = 0;
char* word = malloc(sizeof(char) * maxLength);
while (1)
{
char c = fgetc(file);
if ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
c == '\'')
{
if (length + 1 >= maxLength)
{
maxLength *= 2;
word = realloc(word, maxLength);
}
word[length] = c;
length++;
}
else if (length > 0 || c == EOF)
{
break;
}
}
if (length == 0)
{
free(word);
return NULL;
}
word[length] = '\0';
return word;
}
は、私はエラーを取得する:
Can’t open input1.txt for reading. No such file or directory
なぜこれが動作しませんか?ファイルは確実にそこにあります...
IDEの「現在の」ディレクトリが、あなたが思っているとは限りません。プロジェクト設定をチェックして、現在のディレクトリがどのディレクトリに設定されているかを確認します。あなたの質問を編集して、使用しているIDEを教えてください。もちろん、プログラムの中にいつでもそれを印刷して、それが何であるかを見ることができます。 –
あなたが修正しなければならないことの1つは、 'fopen()'呼び出しが成功したかどうかをチェックして、それは素晴らしいですが、あなたはそれを読むことを試みるanywatに行きます。 –
フルパスを指定して、ファイルを開くか、システム(pwd)を実行して作業ディレクトリを取得してみてください。 – SilentMonk