K
Kuhl
Hi, I am doing programming in Linux system. I need to read data from a
file. See the code below. Such code handles data per byte. But I
usually need to handle data by word (two bytes). If only handle bytes,
then the code is very inefficient. For the sample code in this post,
it is only comparing data, so it's not so serious yet. But in further
parts, I will do a lot of mathematical calculation. Byte operation
would be extremely inefficient. I don't know how to read data from a
file in words. Is there any solution? Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
int main(int argc, char *argv[ ])
{
int fd;
int i;
int gds_size;
char databuf[1024];
struct stat filebuf;
if(stat(argv[1], &filebuf) == -1){
printf("\nERROR: Fail to find file %s .\n", argv[1]);
return 0;
}
fd = open(argv[1], O_RDONLY);
if(fd == -1){
printf("\nERROR: Fail to open file %s .\n", argv[1]);
return 0;
}
read(fd, databuf, 10);
if(!(databuf[0]==0&&databuf[1]==6&&databuf[2]==0&&databuf[3]
==2&&databuf[6]==0&&databuf[7]==28&&databuf[8]==1&&databuf[9]==2)){
printf("\nERROR: This is not a valid GDS format.\n");
close(fd);
return 0;
}
printf("\nFurther program going on.\n");
close(fd);
return 0;
}
file. See the code below. Such code handles data per byte. But I
usually need to handle data by word (two bytes). If only handle bytes,
then the code is very inefficient. For the sample code in this post,
it is only comparing data, so it's not so serious yet. But in further
parts, I will do a lot of mathematical calculation. Byte operation
would be extremely inefficient. I don't know how to read data from a
file in words. Is there any solution? Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
int main(int argc, char *argv[ ])
{
int fd;
int i;
int gds_size;
char databuf[1024];
struct stat filebuf;
if(stat(argv[1], &filebuf) == -1){
printf("\nERROR: Fail to find file %s .\n", argv[1]);
return 0;
}
fd = open(argv[1], O_RDONLY);
if(fd == -1){
printf("\nERROR: Fail to open file %s .\n", argv[1]);
return 0;
}
read(fd, databuf, 10);
if(!(databuf[0]==0&&databuf[1]==6&&databuf[2]==0&&databuf[3]
==2&&databuf[6]==0&&databuf[7]==28&&databuf[8]==1&&databuf[9]==2)){
printf("\nERROR: This is not a valid GDS format.\n");
close(fd);
return 0;
}
printf("\nFurther program going on.\n");
close(fd);
return 0;
}