JohnnyBoy
JohnnyBoy

Reputation: 69

C Unix program won't read from file

I have a basic program that opens a file contained in the same directory as the C file (in root). The file is called myfile1, which is a simple file containing text.

This program is supposed to open the file, count the number of characters and display it. For some reason, I compile the program, run it with a.out and the program gets input from the user and finishes when Ctrl+D is pressed, when it is supposed to get input from the file.

Any ideas as to what could be going on? Thank you very much, here is what I have so far:

#include <fcntl.h>
void main(){
char buff[512];
int fd = 0;
int j=0;
long total=0;

if(fd=open("myfile1",O_RDONLY)<0){
    printf("Error");
    return 1;
}
while((j=read(fd,buff,512))>0)
    total = total+j;
printf("%d\n",total);
close(fd);
return 0;

}

Upvotes: 2

Views: 113

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your code, as ketlat said, the if logic is problematic.

If you put a debug print inside your code and check the fd, you'll see

Code:

if(fd=open("myfile1",O_RDONLY)<0){
    printf("Error");
    return 1;
}
printf("obtained fd = %d\n", fd);

O/P:

obtained fd = 0

Reason

< has higher preceidence over =. Hence, when the open() is success, it will return a non-negative value, which is not less than 0, and the comparison open("myfile1",O_RDONLY)<0 will evaluate to false , represented as 0, and the same will be assigned to fd.

Nw, this fd value will be used in your read() call. FD 0 means stdin or the standard input. So, as per your logic, the code behaves correctly.

However, to achieve your goal, you need to change

fd=open("myfile1",O_RDONLY)<0

to

(fd=open("myfile1",O_RDONLY))<0

With the changed code, a sample run is likely to yield an o/p like

obtained fd = 3.

Be notified, YMMV.

Upvotes: 1

keltar
keltar

Reputation: 18389

The problem is with your if condition: fd=open("myfile1",O_RDONLY)<0. Less-than comparison have higher precedence than assignment. It should be (fd=open("myfile1",O_RDONLY))<0.

Upvotes: 5

Related Questions