Dgrm
Dgrm

Reputation: 133

Simple create - lseek - read program in C

I'm trying to create a simple program which creates a file, writes on it, then moves back the pointer and finally reads it.

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

int main(){ 

  int fd = creat("/home/alum/Class/ej",S_IRWXU);
  if(fd==-1){
    printf("Error %d\n",errno);
    return 1;
  }

  ssize_t size = write(fd, "Halo",4);
  if(size==-1){
    printf("Error %d\n",errno);
    return 1;
  }

  char string[50];
  lseek(fd,0,SEEK_SET);  
  while((size = read(fd, string, 49)) >0){    
    printf("Read[%d]: %s\n",size,string);
  }

  printf("Size: %d\n",size);

  if(size==-1){
    printf("Error %d\n",errno);
    return 1;
  }

  int c=close(fd);
  if(c==-1){
    printf("Error %d\n",errno);
    return 1;
  }

  return 0;
}

My problem is that "lseek" seems not to be working. I always get size "-1" when I try to read, so I assume I'm not going back to the beginning of the file... Any suggestions?

I've seen some questions related to lseek but I haven't found a solution to my problem.

EDIT:

I changed

  int fd = creat("/home/alum/Class/ej",S_IRWXU);

to

  int fd = open("/home/alum/Class/ej",O_CREAT|O_RDONLY|O_WRONLY|O_TRUNC);

and also tried

  int fd = open("/home/alum/Class/ej",O_CREAT|O_RDONLY|O_WRONLY|O_TRUNC,0700);

As suggested but I keep getting the same error.

Upvotes: 0

Views: 555

Answers (1)

Dgrm
Dgrm

Reputation: 133

I had to use

int fd = open("/home/alum/Class/ej",O_CREAT|O_RDWR|O_TRUNC,0700);

to create the file since 'creat' does not work for reading (manpage) and 'open' didn't work as O_RDWR for me if I used O_RDONLY|O_WRONLY.

Upvotes: 1

Related Questions