473,769 Members | 6,305 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Low Level File I/0

emaghero
85 New Member
Greetings and Salutations,

I am currently doing some file I/0 on data that I have and I do not wish to use fstream. I have data stored in its untranslated binary format and I want to read it into another program. I have been using _open and _write to export the data but I have been having problems implementing _read.

I will give a simple example of what I want to do.

The following code creates a file and stores it in some location. The file is in binary format and is open for reading and writing.
Expand|Select|Wrap|Line Numbers
  1.     int data;
  2.     int file=_open("g:\\testfile.rob",_O_BINARY|_O_WRONLY|_O_CREAT|_O_TRUNC,_S_IREAD|_S_IWRITE);
  3.  
  4.     if(file==-1){
  5.         perror("Failed to open file\n");
  6.     }
  7.     else{
  8.         cout<<"file is open\n";
  9.     }
  10.  
  11.     char *header="Test File";
  12.  
  13.     data=_write(file,header,(unsigned int)(strlen(header)));
  14.  
  15.     double arr[20];
  16.  
  17.     srand((unsigned)time(NULL));//Seed the random numbers
  18.  
  19.     //Create an array of random numbers
  20.     for(int i=0;i<20;i++){
  21.         arr[i]=rand()%100;//Create an array of random numbers
  22.     }
  23.  
  24.     //Send these random numbers to the output file
  25.     double val;
  26.     for(int i=0;i<20;i++){
  27.         val=arr[i];
  28.         data=_write(file,(void *)&val,sizeof(double));
  29.     }
  30.  
  31.     _close(file);
  32.  
This works fine once the following have been included
Expand|Select|Wrap|Line Numbers
  1. #include <fcntl.h>
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <io.h>
  5. #include <stdio.h>
  6.  
I have been trying to read the data back from the file using the
Expand|Select|Wrap|Line Numbers
  1. _read("file desciptor", "buffer", "Number of bytes");
  2.  
function. This function is supposed to take a file, similar to the one used above, read in Number of bytes data to the buffer and the return the number of bytes that were read.

Here is what I have attempted to do.

Expand|Select|Wrap|Line Numbers
  1. int data;
  2.     int file=_open("g:\\testfile.rob",_O_BINARY|_O_WRONLY|_O_CREAT|_O_TRUNC,_S_IREAD|_S_IWRITE);
  3.  
  4.     if(file==-1){
  5.         perror("Failed to open file\n");
  6.     }
  7.     else{
  8.         cout<<"file is open\n";
  9.     }
  10.  
  11.     char *header="Test File";
  12.  
  13.     data=_write(file,header,(unsigned int)(strlen(header)));
  14.  
  15.     double arr[20];
  16.  
  17.     srand((unsigned)time(NULL));//Seed the random numbers
  18.  
  19.     //Create an array of random numbers
  20.     for(int i=0;i<20;i++){
  21.         arr[i]=rand()%100;//Create an array of random numbers
  22.     }
  23.  
  24.     //Send these random numbers to the output file
  25.     double val;
  26.     for(int i=0;i<20;i++){
  27.         val=arr[i];
  28.         data=_write(file,(void *)&val,sizeof(double));
  29.     }
  30.  
  31.     char BUF[1024];
  32.  
  33.     int testvar;
  34.  
  35.     unsigned int num=300;
  36.  
  37.     testvar=_read(file,(void *)&BUF,num);
  38.  
  39.     cout<<testvar<<endl;
  40.  
  41.     cout<<BUF<<endl;
  42.  
  43.    _close(file);
  44.  
Upon output the value of testvar is -1, which indicates an error, and the output of BUF is gibberish.

Can anybody suggest a possible remedy.

Any help will be greatly appreciated.
Aug 23 '07 #1
5 2398
emaghero
85 New Member
I have found out why I was getting a return of -1.

Basically I should not have tried to read from the fiel while it was still open.

The following code will produce error free output.

Expand|Select|Wrap|Line Numbers
  1. int data;
  2.     int file=_open("g:\\testfile.rob",_O_BINARY|_O_WRONLY|_O_CREAT|_O_TRUNC,_S_IREAD|_S_IWRITE);
  3.  
  4.     if(file==-1){
  5.         perror("Failed to open file\n");
  6.     }
  7.     else{
  8.         cout<<"file is open\n";
  9.     }
  10.  
  11.     char *header="Test File";
  12.  
  13.     data=_write(file,header,(unsigned int)(strlen(header)));
  14.  
  15.     double arr[20];
  16.  
  17.     srand((unsigned)time(NULL));
  18.  
  19.     //Create an array of random numbers
  20.     for(int i=0;i<20;i++){
  21.         arr[i]=rand()%100;
  22.     }
  23.     //Send these random numbers to the output file
  24.     double val;
  25.     for(int i=0;i<20;i++){
  26.         val=arr[i];
  27.         data=_write(file,(void *)&val,sizeof(double));
  28.     }
  29.  
  30.     _close(file); //Note the closing of the file here and the opening of a new file below
  31.  
  32.     int newfile=_open("g:\\testfile.rob",_S_IREAD);
  33.  
  34.     char BUF[1024];
  35.  
  36.     int testvar;
  37.  
  38.     unsigned int num=600;
  39.  
  40.     testvar=_read(newfile,(void *)&BUF,num);
  41.  
  42.     cout<<testvar<<endl;
  43.  
  44.     cout<<BUF<<endl;
  45.  
  46.     _close(newfile);
  47.  
The output from this code is 169, the number of bytes read from the file, and "Test Header", the head that was assigned at the start.

Can anybody tell me how to extract the numbers that are stored in the file.
This being fairly important for a numerical application.
Aug 23 '07 #2
xoinki
110 New Member
hi,
you can use ascii range for detection..
read everything character by character then check whether it is within the range if it is then it is a number else ignore and continue till EOF.
Regards
Xoinki
Aug 23 '07 #3
RRick
463 Recognized Expert Contributor
The ascii technique is not going to work because the numbers are stored as binary. No ascii conversion was made when the numbers were written to the file.

Instead, you're going to have to treat the buffer as a pointer to doubles. If the index where the double data begins is dInd, then the following will allow you to view buffer as doubles.
Expand|Select|Wrap|Line Numbers
  1. double * dPtr = (double *) & buffer[ dInd];
  2. cout << dPtr[0] << etc.
  3.  
Reading and writing binary data this way is very platform dependent. There are issues like big/little endian byte ordering. Also, the format and precision of the double can change between systems and even compilers.

Becareful how you use this.
Aug 23 '07 #4
emaghero
85 New Member
The ascii technique is not going to work because the numbers are stored as binary. No ascii conversion was made when the numbers were written to the file.

Instead, you're going to have to treat the buffer as a pointer to doubles. If the index where the double data begins is dInd, then the following will allow you to view buffer as doubles.
Expand|Select|Wrap|Line Numbers
  1. double * dPtr = (double *) & buffer[ dInd];
  2. cout << dPtr[0] << etc.
  3.  
Reading and writing binary data this way is very platform dependent. There are issues like big/little endian byte ordering. Also, the format and precision of the double can change between systems and even compilers.

Becareful how you use this.
Hey RRick, thanks very much. That worked quite well. I was thinking of something similar but I couldn't get the syntax right.

With regard to your warning: What is "big/ little endian byte ordering"?

I don't plan on changing compilers so that won't be an issue.
Aug 24 '07 #5
RRick
463 Recognized Expert Contributor
Endian has to do with the byte ordering with ints, longs, doubles, etc. I'll let you google that subject because I always get is backwards. A diagram really helps.

It appears you are doing this for speed and size, but be careful with the low level reads and writes. They are not necessarily buffered which can be expensive when you read/write small chunks of data. The C and C++ routines do support buffering and also support binary data.

I use the low level routines when I want to do a single read or write. I had one job that needed to read and write images. Since I knew how big the largest image was, I could do all my calculations in memory and then write it out with one write. Same thing for reading.
Aug 24 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

2
1475
by: campbell.shaun | last post by:
The application I am writing uses XML files for validation. I've been able to set up my xml files so that I can share validation for common fields using external entities. eg <?xml version="1.0"?> <!DOCTYPE foo > <foo> .... document instance here ... </foo>
3
2511
by: Ais | last post by:
Hi.. Presently i'm trying to install IBM Db2 Software on my Windows XP Operating systems. I'm using IBM(R) DB2(R) Universal Database Enterprise Server Edition, Version 8.1. After installation of the Above , i installed DB2 service Pack FP5_WR21334_ESE.
1
2532
by: raydelex | last post by:
I am new to securing a database with logins. My questions is: I want only one database to use a new Workgroup file that I have created, not all the Access databases that I bring up under my system login. Can this be done? Thanks
5
2278
by: rdcpro | last post by:
In reading MSDN docs on creating custom Configuration sections, I found this page: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfcustomelementfornamevaluesectionhandlerdictionarysectionhandler.asp At the very bottom, it says: Configuration File This element can be used in the application configuration file, machine configuration file (Machine.config), and Web.config files that are not at the
0
1871
by: accessman2 | last post by:
I have a question. I want to open the MS Access file with user-level Security. I know that if I do NOT setup user-level Security in the MS Access file, and create the table for login in the MS Access file (Put the MS Access file in the server), then it works. I did that. But, I want to know whether or not we can use ASP code to open the MS Access (MS Access user-level Security setting). This way I can put the MS Access file in the public...
2
1477
by: RanjitSingh.RS | last post by:
I have several Databases in a Instance . I want to a set particular Isolation Level for Only one read Only Database . Is it Possible to set a specific Isloation Level at a Database Level
2
1228
by: FP | last post by:
I have the following files; \A.php \F1\B.php \F1\F1_1\C.php File A has the lines "echo 'A'; include_once('F1/B.php');" File B has the lines "echo 'B'; include_once('F2/C.php');" File C has the line "echo 'C';" If I open file A in my browser I get "ABC".
6
4068
by: GrispernMix | last post by:
//ques and and level order traversal file name: lab6_build_leaf_up.cpp Instructions:
7
2836
by: GrispernMix | last post by:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include <iostream> #include <string.h> using namespace std; #define TRUE 1 #define FALSE 0
10
15587
by: =?Utf-8?B?YzY3NjIyOA==?= | last post by:
Hi all, I had a program and it always works fine and suddenly it gives me the following message when a pass a xml file to our server program: error code: -1072896680 reason: XML document must have a top level element. line #: 0 I don't know if it is my xml file or it is something else? Here is my client side program: <%@ Language=vbScript%>
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9993
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8870
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3958
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.