01 Reading Files
Return Value¶
| Return Value | Read Successful? | Return Value |
|---|---|---|
| \(>= 0\) | β | no of bytes read |
| \(< 0\) | β |
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd;
char content[100]="\0";
fd = open(argv[1], O_RDONLY);
if(fd < 0)
{
printf("File could not be opened.\n");
return 1;
}
else
{
read(fd, content, sizeof(content)-1);
write(1, content, sizeof(content)-1);
}
return 0;
}
argcstands for argument count and argv stands for argument valuesopen: Used to Open the file for reading, writing or both.int open (const char* Path, int flags [, int mode ]);
- Flags
O_RDONLY: read onlyO_WRONLY: write onlyO_RDWR: read and write,O_CREAT: create file if it doesnβt existO_EXCL: prevent creation if it already exists
2023-01-25