약간 전제 : 서버가 소켓을 통해 "get text.txt"메시지를 수신 중입니다. 파일 크기를 계산하여 다시 보내야합니다. 지금까지 번호 :문자열의 파일 경로에서 파일 크기를 계산합니다.
/*Receive command
*
*/
char * file_path;
//Wait for command
if (recvfrom (sockfd_child, command, PACKET_SIZE, 0, (struct sockaddr *) addr_client, &addr_client_lenght) < 0) {
perror("server: error in recvfrom for command packet");
exit(1);
}
//check first 4 character (COMMAND_SIZE) of command packet send by the client to identify the operation
if (!strncmp(command, "get ", COMMAND_SIZE)) {
file_path = malloc(sizeof(command)-COMMAND_SIZE);
strcpy(file_path, DIRECTORY);
strncat(file_path, command+COMMAND_SIZE, PACKET_SIZE-COMMAND_SIZE);
printf("Getting file in path: '%s'\n", file_path);
int file_size = get_file_size(file_path);
FILE_SIZE를 계산하는 함수
long get_file_size(char * file_name) {
long size;
FILE * file;
if (!(file = fopen (file_name , "rb"))) {
perror("file: error calculating size");
exit (1);
}
fseek (file , 0 , SEEK_END);
size = ftell (file);
rewind (file);
fclose(file);
return size;
}
DIRECTORY는 상수이고, 4
설정된다
COMMAND_SIZE을 ./files/로 설정된 0 프로그램의 네트워크 부분이 잘 작동하고 명령 문자열이 성공적으로 전송됩니다.
프로그램은 perror 인쇄 file: error calculating size: No such file or directory
에서 기능에서 멈추지 만 이전 인쇄물은 파일이있는 곳에 올바른 경로를 인쇄합니다. Getting file in path: './files/text.txt'
그래서 'get'또는 다른 곳에있는 파일 경로를 구분하는 방법에 오류가있는 것 같습니다 나는 이해할 수 없다. 나 좀 도와 줄 수있어? 실수 나 혼란에 대한 죄송하지만 여기에 오전 4시입니다 :)
다른 사용자가 테스트 할 수있는 예를 만드십시오. 여기의 지침도 참조하십시오. http : //stackoverflow.com/tags/c/info – Jasen
상대 경로로 작업하고 있으므로 대략적인 추측 : 서버 프로세스는 아마 당신이 생각하는 것이 아닙니다. getcwd를 사용하여 현재 작업 디렉토리를 가져 와서 인쇄하십시오. './files/test.txt'는 그 디렉토리에 상대적으로 존재합니까? – Wintermute
파일 크기를 계산할 때,'fsetpos()'와'fgetpos()'함수를 고려하십시오. 이들에 사용 된 정수는 OS에 맞는 크기입니다. 'fseek()'와'ftell()'에 의해 사용되는'long'은 충분하지 않을 수 있습니다. – chux