Results 1 to 9 of 9

Thread: Basic File I/O

  1. #1
    Guest

    Post

    Ok, someone posted some file i/o functions, but they did a little to much. What i need is the basic code to save and open a file. No error checking or anything like that, it needs to be as basic as possible. This is for windows. And the functions i need at this moment are to open a file, save to a file, and see if a file exist. Thank you.

  2. #2
    Guest
    I wrote a class that uses <fstream>, it writes to files, and opens them, but I didn't write any file exist functions yet... but it shouldn't be too hard.

    http://www.planetsourcecode.com/xq/A...s/ShowCode.htm


    -Dennis

  3. #3
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    DirectFile.h
    Code:
    #ifndef __DIRECTFILE_H__
    #define __DIRECTFILE_H__
    
    #include <io.h>
    #include <fcntl.h>
    #include <sys/stat.h>
    #include <string.h>
    #include <mjp/Defines.h>
    
    /// Simplifies low-level disk access without the need for the stdio library.
    class DirectFile {
    public:
    	/// Constructor sets the internal file handle to an illegal value.
    	DirectFile() {
    		m_iFD = -1;
    	}
    
    	/// Empty destructor, could automatically close file.
    	virtual ~DirectFile() {
    		//Close();
    	}
    
    	/** Open a file for reading.
    		@param pcFilename File to open
    		@param bBinary Whether or not to perform newline conversions
    	 **/
    	bool OpenRead(char *pcFilename, bool bBinary) {
    		if(m_iFD != -1) {
    			return false;
    		}
    		m_iFD = _open(pcFilename, (bBinary ? _O_BINARY : _O_TEXT) | _O_RANDOM | _O_RDONLY);
    		if(m_iFD == -1)
    			return false;
    		m_bMode = false;
    		return true;
    	}
    
    	/** Open a file for writing.
    		@param pcFilename File to open
    		@param bCreate Whether to create the file if it doesn't exist already
    		@param bBinary Whether or not to perform newline conversions
    		@param bAppend Whether or not to overwrite a file that is already present
    		@return Success or failure
    	 **/
    	bool OpenWrite(const char *pcFilename, bool bCreate, bool bBinary, bool bAppend) {
    		if(m_iFD != -1) {
    			return false;
    		}
    		m_iFD = _open(pcFilename, (bBinary ? _O_BINARY : _O_TEXT) | (bCreate ? _O_CREAT : 0) | _O_RANDOM | _O_RDWR | (bAppend ? _O_APPEND : _O_TRUNC), _S_IREAD | _S_IWRITE);
    		if(m_iFD == -1)
    			return false;
    		m_bMode = true;
    		return true;
    	}
    
    	/** Close the current open file
    		@return Success or failure
    	 **/
    	bool Close() {
    		if(m_iFD != -1) {
    			int iResult = _close(m_iFD);
    			m_iFD = -1;
    			if(iResult == -1)
    				return false;
    			if(iResult == 0)
    				return true;
    		}
    		return false;
    	}
    
    	/** Write data to a file
    		@param pData Pointer to the data block
    		@param nSize Size in bytes of each data item
    		@param nCount Number of data items
    		@return Number of data items written
    	 **/
    	int Write(void *pData, int nSize, int nCount) {
    		if((m_iFD == -1) || (m_bMode == false))
    			return -1;
    
    		int iCount = _write(m_iFD, pData, nCount * nSize);
    		if(iCount == -1)
    			return -1;
    
    		return (iCount / nSize);
    	}
    
    	/** Read data from a file
    		@param pData Pointer to the data block
    		@param nSize Size in bytes of each data item
    		@param nCount Number of data items
    		@return Number of data items read
    	 **/
    	int Read(void *pBuffer, int nSize, int nCount) {
    		if((m_iFD == -1) || (m_bMode == true))
    			return -1;
    
    		int iCount = _read(m_iFD, pBuffer, nCount * nSize);
    		if(iCount == -1)
    			return -1;
    		return (iCount / nSize);
    	}
    
    	/** Get current file position.
    		@return Current file position
    	 **/
    	long GetPos() {
    		if(m_iFD == -1)
    			return -1;
    		return _tell(m_iFD);
    	}
    
    	/** Seek to a specific part of the file
    		@param lOffset Offset in bytes from position represented by lOrigin
    		@param lOrigin Origin point: beginning, end, or set
    		@return Previous position
    	 **/
    	long Seek(long lOffset, long lOrigin) {
    		if(m_iFD == -1)
    			return -1;
    		return _lseek(m_iFD, lOffset, lOrigin);
    	}
    
    	/** Get file length
    		@return Length (in bytes) of file
    	 **/
    	long Length() {
    		if(m_iFD == -1)
    			return -1;
    		return _filelength(m_iFD);
    	}
    
    	int m_iFD; ///< Current file handle
    	bool m_bMode; ///< File mode (true=write, false=read)
    };
    
    #endif // __DIRECTFILE_H__
    Defines.h
    Code:
    #ifndef __DEFINES_H__
    #define __DEFINES_H__
    
    #define CHAR_PTR(x)		((char*)&(x)) /**< Convert first character into array pointer */
    #define FILE_SYSTEM		0x1 /**< System file */
    #define FILE_ARCHIVE	0x2 /**< Archived file */
    #define FILE_READONLY	0x4 /**< Read-only file */
    #define FILE_HIDDEN		0x8 /**< Hidden file */
    
    #ifndef NULL
    #ifdef  __cplusplus
    #define NULL    0
    #else
    #define NULL    ((void *)0)
    #endif
    #endif
    
    typedef unsigned char ubyte; /**< Unsigned byte */
    typedef signed char sbyte; /**< Signed byte */
    
    typedef unsigned short ushort; /**< Unsigned byte pair */
    typedef signed short sshort; /**< Signed byte pair */
    
    typedef unsigned long ulong; /**< Unsigned byte quad */
    typedef signed long slong; /**< Signed byte quad */
    
    typedef unsigned int uint; /**< Unsigned integer */
    typedef signed int sint; /**< Signed integer */
    
    #endif // __DEFINES_H__
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  4. #4
    Frenzied Member Vlatko's Avatar
    Join Date
    Aug 2000
    Location
    Skopje, Macedonia
    Posts
    1,409
    Here are some fuctions using only API:
    Code:
    BOOL SaveFile(HWND hEdit, LPSTR pszFileName)
    {
       HANDLE hFile;
       BOOL bSuccess = FALSE;
    
       hFile = CreateFile(pszFileName, GENERIC_WRITE, NULL, NULL,
          CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
       if(hFile != INVALID_HANDLE_VALUE)
       {
          DWORD dwTextLength;
          dwTextLength = GetWindowTextLength(hEdit);
          if(dwTextLength > 0)// No need to bother if there's no text.
          {
             LPSTR pszText;
             pszText = (char*)GlobalAlloc(GPTR, dwTextLength + 1);
             if(pszText != NULL)
             {
                if(GetWindowText(hEdit, pszText, dwTextLength + 1))
                {
                   DWORD dwWritten;
                   if(WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL))
                      bSuccess = TRUE;
                }
                GlobalFree(pszText);
             }
          }
          CloseHandle(hFile);
       }
       return bSuccess;
    }
    
    BOOL LoadFile(HWND hEdit, LPSTR pszFileName)
    {
       HANDLE hFile;
       BOOL bSuccess = FALSE;
    
       hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
          OPEN_EXISTING, NULL, NULL);
       if(hFile != INVALID_HANDLE_VALUE)
       {
          DWORD dwFileSize;
          dwFileSize = GetFileSize(hFile, NULL);
          if(dwFileSize != 0xFFFFFFFF)
          {
             LPSTR pszFileText;
             pszFileText = (char*)GlobalAlloc(GPTR, dwFileSize + 1);
             if(pszFileText != NULL)
             {
                DWORD dwRead;
                if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL))
                {
                   pszFileText[dwFileSize] = 0; // Null terminator
                   if(SetWindowText(hEdit, pszFileText))
                      bSuccess = TRUE; // It worked!
                }
                GlobalFree(pszFileText);
             }
          }
          CloseHandle(hFile);
       }
       return bSuccess;
    }
    I am become death, the destroyer of worlds.
    mail:[email protected]

    • Visual Basic 6.0 & .NET
    • Visual C++ 6.0 & .NET
    • ASP
    • LISP
    • PROLOG
    • C
    • Pascal

  5. #5
    Guest
    Ok, those are the functions i was talking about

  6. #6
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Which were?

    Vlatko's Windows ones, or my library ones?
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  7. #7
    Guest
    Vlatko's.

  8. #8
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Fair enough.

    Incidentally, if anyone has any information as to which are the actual low-level functions, I'd be grateful for it.

    What I mean - does CreateFile call _open, or does _open call CreateFile?
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  9. #9
    Hyperactive Member Wak's Avatar
    Join Date
    Nov 2000
    Location
    Brisbane, Queensland
    Posts
    298

    Talking _creat and _write easier thean Create and Write

    Code:
    // StringSave.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include "io.h"
    #include "fcntl.h"
    #include "sys\stat.h"
    #include "string.h"
    
    
    int main(int argc, char* argv[])
    {	
    	int hFile = _creat("test.txt", _S_IWRITE|_S_IREAD);
    
    	char* pszTxt = "This is my test Text!!";
    
    	_write(hFile, pszTxt, strlen(pszTxt));
    	_close(hFile);
    
    	hFile = _open("test.txt", _O_RDONLY);
    
    	_lseek(hFile, 0L, SEEK_END);
    	int nLen = _tell(hFile)-1;
    	char szBuf;
    	while(nLen>=0)
    	{
    		_lseek(hFile, nLen--, SEEK_SET);
    		_read(hFile, &szBuf, 1);
    		_write(1, &szBuf, 1);
    	}
    
    	return _close(hFile);
    }
    
    //StdAfx.h  is just like the normal built in file
    Hope it works.

    Visual Basic 6.0 Enterprise
    Visual C++ 6.0 Professional

    Wak

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width