help with opening files and reading them in C


 
Thread Tools Search this Thread
Top Forums Programming help with opening files and reading them in C
# 1  
Old 02-10-2011
Error help with opening files and reading them in C

In C, given a name or path to a file, how do I check if the path is valid, and how can I check its permisions will let me read from it, and how do i check if its an empty file?
# 2  
Old 02-10-2011
Code:
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
// questions 1 & 2:
// access validates access to a file  F_OK == path is okay and file exists  
//  R_OK == F_OK + I can read it, so use R_OK
// Q3:
// this is a general function to get the size of an opened file
size_t filesize(int fd)
{
    struct stat st;
    if(fstat(fd, &st)== -1)
    {
          perror("Cannot stat file");
          exit(1);
    }
    return st.st_size;
}
int main(int argc, char **argv)
{
    FILE *in=NULL; 
    
    if(access(argv[1], R_OK)==0)
    {
           printf("file %s, access is okay\n", argv[1]);
    }
    in=fopen(argv[1],"r");
    printf("file size = %u\n", filesize(fileno(in));
    fclose(in);
    return 0;
}

# 3  
Old 02-10-2011
when doing the access command i am getting this error


:108: error: âR_OKâ undeclared (first use in this function)
108: error: (Each undeclared identifier is reported only once
108: error: for each function it appears in.)
# 4  
Old 02-10-2011
Vave you included unistd.h? What operating system are you on?

Also note that
Code:
   printf("file size = %u\n", filesize(fileno(in));

should be
Code:
   printf("file size = %u\n", filesize(fileno(in)) );

# 5  
Old 02-10-2011
oh i missed that, now i got it
# 6  
Old 02-10-2011
Quote:
Originally Posted by omega666
In C, given a name or path to a file, how do I check if the path is valid, and how can I check its permisions will let me read from it, and how do i check if its an empty file?
Like this:

Code:
int fd = open( pathToFile, O_RDONLY );

Anything else is extraneous - there's no point in using access() on a path just to check if if exists if you're going to open it for reading - the open will do that for you. If it doesn't exist, the open() call will fail with errno set to EEXIST. There's no point in checking if the permissions allow you to read the file, because if you can't the open will fail with errno set to either EPERM or EACCESS (I forget offhand which one it will be).

If it's empty, when you read from it you'll get zero bytes.

There's no point in checking to see if you can or can't do something - just make the call to do it and check your return status.

You DO check return status ALWAYS, don't you?
# 7  
Old 02-10-2011
i'm am trying to read a unix word list file, using this code
Code:
int u=1;
char line[11];
    int length;
FILE *fr;
fr = fopen ("/usr/share/dict/words", "r");
while (fgets(line, 11, fr) != NULL) {
 length = str_len(&line);
 printf(line);
 printf("\n%d %d\n",length,u);
u++;
}

and for some reason i get stuff like empty strings
this is part of the output:


2 134536
hemoscope
9 134537

0 134538
hemoscopy
9 134539

0 134540
hemosider
9 134541
in
2 134542


why is this happenning?
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Loop Script and not opening files containing spaces

Hello, I wrote a simple script, that basically wait for a *.dat-file in a certain folder, which is always a zipped file and extracts it. It worked before and i changed nothing in the script, but since last week i have the problem, that it doesnt extract files containing a space. How do i make... (4 Replies)
Discussion started by: blend_in
4 Replies

2. Shell Programming and Scripting

Perl-opening a file then copying files

Good morning guys!! Im still practicing with Perl and now Im trying to open a file, and copy its contents to another file. Them I want to remeove the information out of the orginal file after it is copied over. The flow should be messages-->messages1-->messages2. Kind of like a log... (1 Reply)
Discussion started by: bigben1220
1 Replies

3. Shell Programming and Scripting

Opening Mulitple files using For loop in Perl

Hi All, I have a total of ten file to open in the Perl script and i am using a for loop to open each file and capture some strings inside each file. Unfortunately, i encounter the below syntax error. I think there should be something wrong with this term reports_${counting}_${_}.txt but i do... (4 Replies)
Discussion started by: Raynon
4 Replies

4. Web Development

opening text files with javascript

Im aware under IE, javascript uses ActiveX Objects to open up and manipulate text files, excel files etc.. How abouts would I open a text file using javascript in Firefox ? thanks (1 Reply)
Discussion started by: JamesGoh
1 Replies

5. Shell Programming and Scripting

error while opening files in a directory

I tried opening the files in a directory and print thier names. But it was thowing the error "unable to open directorty at t5.pl line 2." Can u plz correct this error in below mentioned code. #!/data/scoredev/perl opendir(HOMEDIR,"c:\vin") || die("unable to open directorty");... (3 Replies)
Discussion started by: vinay123
3 Replies

6. Shell Programming and Scripting

Opening Files as command line arguments

Hi have set a command line argument where the user enters the filename. I have set a condition that if the command line is null (user just enters return), the script will exit (with an error message). However, what if the user types something and the file isn't found. How will I go about... (20 Replies)
Discussion started by: Cactus Jack
20 Replies

7. UNIX for Dummies Questions & Answers

Opening Files in append mode

Is there any other way to open a file in append mode without using C calls or >> redirection? (1 Reply)
Discussion started by: vidhya
1 Replies

8. UNIX for Dummies Questions & Answers

opening non-html files in lynx??

when i try to open a txt file in lynx I need to provide the filename or use wildcards to open. Autocompletion doesn't work for some reason. Also, trying to open files like: .sh, .py etc. ends up in the following error: lynx: Start file could not be found or is not text/html or text/plain ... (0 Replies)
Discussion started by: riwa
0 Replies

9. UNIX for Dummies Questions & Answers

Opening files

I am very new to unix. I want to open a file and read one line in at a time. Can anybody help? (3 Replies)
Discussion started by: saarshad001
3 Replies

10. UNIX for Dummies Questions & Answers

Opening Files

I'm a new to UNIX/LINUX. I just put cygwin on my laptop and I can navigate around the directories, but I can't open files (.doc, .ppt, .html or .exe). Is there an explicit command to do this? I know that in Solaris when it does not recognize the file, it brings up the list of available viewing... (4 Replies)
Discussion started by: AJA
4 Replies
Login or Register to Ask a Question