Home arrow C and C+ arrow Reading From a File in C Language Using System Functions
Reading From a File in C Language Using System Functions PDF
Wednesday, 08 February 2012
Next example show how to read data from a file in C language using system functions. To test the program use packet file. Or, you can generate this file using C code from Writting to a File in C Using System Functions.

read_from_file.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

struct packet {
    uint16_t source;
    uint16_t dest;
    uint16_t length;
    uint16_t checksum;
    char data[32];
};

typedef struct packet packet;

void read_packet(char *filename)
{
packet p;
int fd;

fd = open(filename, O_RDONLY);
read(fd, &p.source ,2);
read(fd, &p.dest ,2);
read(fd, &p.length ,2);
read(fd, &p.checksum ,2);
read(fd, &p.data ,32);

printf("\nPacket Source: %d", p.source);
printf("\nPacket Dest: %d", p.dest);
printf("\nPacket Length: %d", p.length);
printf("\nPacket Checksum: %d", p.checksum);
printf("\nPacket Checksum: %s", p.data);

close(fd);
}

int main(int argc, char *argv[])
{
read_packet("packet");
printf("\n");
return 0;
}


Last Updated ( Wednesday, 08 February 2012 )
 
< Prev   Next >

Other BSD Systems

OpenBSD

Misc

Solaris

Polls

Best BSD firewall?