The open() function returns an integer value, which is used as a handle. If unsuccessful it returns -1.
int open(char *filename,char *mode);
The available access modes are
r read: Open file for input operations. The file must exist.
w write: Create an empty file for output operations.
a append: Open file for output at the end of a file.
r+ read/update: Open a file for update. The file must exist.
w+ write/update: Create an empty file and open it for update (both for input and output).
a+ append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file.
#define EMBEDTRON "www.embedtron.com"
#define BUFFER_SIZE 20
int main()
{
char buffer[BUFFER_SIZE];
int len = 0;
int fh = 1;
if((fh=open("file.txt","w" )) == -1)
{
printf("Create file failed");
return -1;
}
if((len = write(fh,EMBEDTRON,strlen(EMBEDTRON))) != strlen(EMBEDTRON))
{
printf("Write data failed");
return -2;
}
close(fh);
if((fh=open("file.txt","r" )) == -1)
{
printf("Create file failed");
return -1;
}
lseek(fh, 0, SEEK_END);
len = tell(fh);
lseek(fh, 0, SEEK_SET);
if((len = read(fh,buffer,BUFFER_SIZE)) != strlen(EMBEDTRON))
{
printf("Read data failed");
return -3;
}
buffer[len] = '\0';
printf("String = %s Size = %d \n",buffer,len);
close(fh);
return 0;
}