Writting to a File in C Language Using System Functions |
![]() |
Wednesday, 08 February 2012 | |
The following example shows you how to write to a file using C system functions: write_to_file.c #include <stdlib.h>#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> struct packet { uint16_t source; uint16_t dest; uint16_t length; uint16_t checksum; char data[32]; }; typedef struct packet packet; void write_packet(char *filename) { packet p; int fd; p.source=9080; p.dest=22; p.length=64; p.checksum=1200; strcpy(p.data, "ssh connection"); /*if(fd = open(filename, O_WRONLY) == 0) { printf("\nCannot open file.\n"); exit(1); } */ fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0644 ); write(fd, &p.source ,2); write(fd, &p.dest ,2); write(fd, &p.length ,2); write(fd, &p.checksum ,2); write(fd, &p.data ,32); close(fd); } int main(int argc, char *argv[]) { write_packet("packet"); printf("\n"); return 0; } |
< Prev | Next > |
---|