Linux环境下程序执行路径的问题
执行程序目录即为当前目录
例如
#执行程序
yourhost:~/Documents/codes/CCodes$ ./getc_test
#那么当前目录即为
~/Documents/codes/CCodes
如果在程序中指定文件目录为"filename",则文件应该在~/Documents/codes/CCodes
如果在程序中指定文件目录为"…/filename",则文件应该在~/Documents/codes
测试程序如下
程序结构
|---------bin:可执行文件
|---------sources:
|-----------------------getc_test.c
|---------Makefile
|---------Hellotest.text
Makefile文件
CC = gcc
CFLAGS = -W -Wall -O2
INC =
TARGETS = bin/getc_test
SRC_DIR = sources
all:$(TARGETS)
$(TARGETS):
@echo "start compiling..."
$(CC) $(CFLAGS) $(SRC_DIR)/getc_test.c -o bin/getc_test
clean:
rm -rf bin/*
.c文件
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
int main()
{
/*if(open("../HelloTest.txt",O_RDWR) < 0)*/
/*{*/
/*printf("open error\n");*/
/*return -1;*/
/*}*/
FILE* fd;
if((fd = fopen("HelloTest.txt", "rw")) == NULL)
{
printf("fopen error");
return -1;
}
printf("-------------------------\n");
char ch = fgetc(fd);
while (ch != EOF) {
putchar(ch);
ch = fgetc(fd);
}
fclose(fd);
}