LINUX.ORG.RU

Использовать stat для проверки файла на существование.


0

0

Собственно сабж. Хотелось бы узнать можно ли использовать функцию stat для проверки того, существует файл или нет. Заранее спасибо тем, кто поможет. Не хочется просто access держать только для проверки файла на существование.

★★★

Последнее исправление: Dorif (всего исправлений: 1)
Ответ на: комментарий от Dorif

>Меняю тип на int- орёт, что функция НЕ возвращает значения.)))

все логично, если условие не сработает, то функция в твоем случае не вернет значения, а должна вернуть в любом случае.

И в обоих случаях использование проги по отношению к несуществующим файлам приводит к сегфолту


нужно открыть man-страницу fopen и прочитать что и при каких условиях возвращает эта функция, повторить для open и увидеть поразительное сходство, а далее написать обработку ошибок для fopen.
з.ы.:
http://lxr.linux.no/#linux+v2.6.34.1/Documentation/CodingStyle

rg-400
()
Ответ на: комментарий от rg-400

Примерно так?

if (f == NULL) { 
                switch (errno) { 
                case EISDIR: 
                    fprintf(stderr, "File %s is directory.\n",argv[1]); 
                    break; 
                default: 
                    fprintf(stderr, "cannot open file- %s\n", 
                               strerror(errno)); 
                }                
                return 1; 
        } 
Один вопрос: значение errno, соответствующее тому, что файл не найден? ENOENT или что- то другое?

Dorif ★★★
() автор топика
Ответ на: комментарий от rg-400

Спасибо большое! Вот новая реализация:

/*     cloncat.c
  
Copyright 2010 Alexandr Dorif <dorif11@gmail.com>
 
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
  
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
   
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.*/
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <string.h> 
int help();
int fchk(const char *fn);
int main(int argc, char **argv){
	if(argc==3) if(!strcmp(argv[1],"-n")||!strcmp(argv[1],"--number")){
		FILE *f=fopen(argv[2],"r");
		if(f==NULL)fchk(argv[2]);
		int a,i;
		i=1;
		printf("1:");
		while(feof(f)==0){
			a=fgetc(f);
			if(a=='\n'){
			long pos;
			pos=ftell(f);
			fseek(f,1,SEEK_CUR);
			if(fgetc(f)==EOF){
				putchar(a);
				fclose(f);
				return 0;
				}
			else printf("\n%d: ",++i);
			fseek(f,pos,SEEK_SET);
			}
		else putchar(a);
		}
	}
		else help();
	else if(argc>3||argc==1||!strcmp(argv[1],"-h")||!strcmp(argv[1],"--help")) help();
	else{
		if(!strcmp(argv[1],"-v")||(!strcmp(argv[1],"--version"))){
		printf("cloncat version 0.4\n");
		return 0;
	}
	else{
		FILE *f=fopen(argv[1],"r");
		if (f==NULL)fchk(argv[1]);
		long pos;
		fseek(f,0,SEEK_END);
		pos=ftell(f)-1;
		fseek(f,0,SEEK_SET);
		for(int i;i<=pos;++i)putchar(fgetc(f));
		fclose(f);
		return 0;
	}
}
}
int help(){
		printf("usage: cloncat filefn\n"
		"-h or --help for help\n"
		"-v or --version displays version and exit\n"
		"-n or --number number the output lines\n");
		return 0;
	}
int fchk(const char *fn){  
                switch(errno) {  
					case EISDIR:  
						fprintf(stderr, "File %s is directory.\n",fn);  
						break;
                    case ENOENT:
						fprintf(stderr, "File %s does not exist.\n",fn);
						break;
					case EACCES:
						fprintf(stderr, "Access to file %s denied.\n",fn);
						break;
					default:  
                    fprintf(stderr, "cannot open file- %s\n",strerror(errno));
                    break;
                }                 
                return 1;
			}

Dorif ★★★
() автор топика
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.