?
Solved

Reading an array of characters from a data file

Posted on 2003-03-03
13
Medium Priority
?
221 Views
Last Modified: 2010-08-05
I am a newbie that is trying to read a line from a data file into an array of characters.  I know how to read a string in but that will not work.  I am guessing the code would look something like this:

char arrayName[20];
ifstream infile; //input file object
infile.open("address.txt");
infile.getline(arrayName,20,'\n');

thanks in advance
0
Comment
Question by:packman25
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 2
  • +2
13 Comments
 
LVL 8

Accepted Solution

by:
Exceter earned 200 total points
ID: 8058364
Your code is fine, try this,

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
     char line[50];

     ifstream in("test.txt");
     
     in.getline(line,49,'\n');

     in.close();

     cout << line << endl;

     return 0;
}

-- Test.txt --

This is a test.

-- output --

This is a test.

Exceter
0
 
LVL 11

Expert Comment

by:bcladd
ID: 8058431
Just curious: Why won't reading in a string work? Using the built-in data structres to handle variable sized data is often more flexible than hard-coding limits into a program.

-bcl
0
 
LVL 12

Expert Comment

by:Salte
ID: 8058476
Your code is fine as long as the line is no longer than 20 characters including the terminating null byte. Also, be aware that getline reads everything up to but not including the delimiter and stops when number of characters read equals the size of the buffer. Again, I believe that size includes the terminating null byte so it will actually stop before the value n to getline.

In other words, if every line is 19 characters or less the getline(arrayName,20,'\n'); should work fine.

Be aware that the delimiter ('\n') will be the next character in the buffer and isn't read yet so you need to do an ignore() or something to get rid of it.

infile.ignore(1024,'\n'); should get rid of that '\n' character. Be aware that as the call is specified, if the next 1024 characters are not '\n' it will only read 1024 chars and then the next char will be the next char to read. However, I believe that surely the line must be less than 1044 characters (20 chars from getline + 1024 from ignore) so that should work fine.

Note that if you do ignore and the line is longer than 19 characters, only the 19 first characters will actually be read, the characters after those 19 up to and including the next '\n' will be ignored.

Alf
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 8

Expert Comment

by:Exceter
ID: 8058502
>> I believe that size includes the terminating null byte

Correct.
0
 
LVL 2

Expert Comment

by:xyzzer
ID: 8058510
Or You can go straight to Windows approach and write:

#include <windows.h>
#define MAX_READ_BUF 200000
#define MYASSERT(a,b) if (!a) { errhandler(b); return 0; }

void errhandler(char *str) {
  char *lpMsgBuf;
  FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, // source and processing options
    NULL, // pointer to  message source
    GetLastError(), // requested message identifier
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language // language identifier for requested message
    (LPTSTR) &lpMsgBuf, // pointer to message buffer
    0, // maximum size of message buffer
    NULL); // address of array of message inserts
  MessageBox(GetActiveWindow(), lpMsgBuf, str, MB_OK|MB_ICONEXCLAMATION);
  LocalFree(lpMsgBuf);
}

char *ReadFile(char *FilePath)
{
  HANDLE FileHandle;
  BY_HANDLE_FILE_INFORMATION FileInfo;
  DWORD nFileSizeLow, BytesRead;
  char *ReadBuffer;

//Open file
  FileHandle = CreateFile(
    FilePath, //lpFileName
    GENERIC_READ, //dwDesiredAccess
    FILE_SHARE_READ, //dwShareMode
    NULL, //lpSecurityAttributes
    OPEN_EXISTING, //dwCreationDisposition
    FILE_ATTRIBUTE_NORMAL, //dwFlagsAndAttributes
    NULL);
  MYASSERT((FileHandle != INVALID_HANDLE_VALUE), "Problems opening the file!");

//Read in file info...
  MYASSERT(GetFileInformationByHandle(FileHandle, &FileInfo), "Problems reading the file info!");
  nFileSizeLow = FileInfo.nFileSizeLow;
  MYASSERT(nFileSizeLow, "Empty File!");

  MYASSERT((nFileSizeLow < MAX_READ_BUF), "Too big file to read in!");

//Memory allocation for read buffer
  ReadBuffer = (char*)GlobalAlloc(GMEM_FIXED, nFileSizeLow);
  MYASSERT(ReadBuffer, "Problems allocating buffer memory!");

//Read the file in
  MYASSERT(ReadFile(
    FileHandle,
    ReadBuffer,
    nFileSizeLow,
    &BytesRead, // LPDWORD lpNumberOfBytesRead
    NULL/*LPOVERLAPPED lpOverlapped*/), "Problem z odczytem pliku konfiguracyjnego pomocy!");
  MYASSERT((BytesRead == nFileSizeLow), "Unsuccessful read!");

//Close the read file
  MYASSERT(CloseHandle(FileHandle),"Problems closing the file!");
  return ReadBuffer;

//Remember to GlobalFree the obtained buffer like:
//  MYASSERT(!GlobalFree((HGLOBAL)ReadBuffer), "Problems closing the input file!");
}




This approach handles a few possible simple errors and might be good in commercial implementations. Am I right?
Not a must for everybody, though, to use those Windows functions.
0
 
LVL 8

Expert Comment

by:Exceter
ID: 8058525
Gadzooks!!!

xyzzer, isn't that a little complicated for a task as simple as reading a line of text from disk?

Exceter
0
 
LVL 2

Expert Comment

by:xyzzer
ID: 8058596
Funny You ask. I actually agree! :]
Windows takes QUITE A FEW parameters in its simple functions. And I know it's not a case for beginners. I was just curious if people might consider this useful to check all those assertions and stuff. Might be good for debugging though. Now, if a customer of ours calls us saying that the program crashes saying that "the library called ...dll could not be opened" - we know exactly what happened, even if the person claims the file is there to read... which happens

--Filip
0
 
LVL 12

Expert Comment

by:Salte
ID: 8058618
I also see that he included a call to LocalFree(). As far as I know that is a depreceated function from Win32, it's a leftover from old Win 3.1 and should be avoided.

Similarly specifying FormatMessage with FORMAT_MESSAGE_ALLOCATE_BUFFER is a bad idea.

Then it is better to do it in a two stage processing where you first call FormatMessage to have it return the length of the buffer needed and then doing a new char[length + 1] and then calling FormatMessage again with the same arguments (well, buffer is added instead of the null pointer first time) and then using that buffer and free it after.

However, FormatMessage is a bad idea unless you really have message to format. If all you want is to get a string of data from file and then process that string then FormatMessage is really not the right choice, it's like trying to get an airplane in order to go on a hiking trip in the mountains (assuming those mountains are just outside your home and you don't have to fly to get there). It solves a problem but not exactly the problem you have at hand.

Alf
0
 
LVL 2

Expert Comment

by:xyzzer
ID: 8058626
Funny You ask. I actually agree! :]
Windows takes QUITE A FEW parameters in its simple functions. And I know it's not a case for beginners. I was just curious if people might consider this useful to check all those assertions and stuff. Might be good for debugging though. Now, if a customer of ours calls us saying that the program crashes saying that "the library called ...dll could not be opened" - we know exactly what happened, even if the person claims the file is there to read... which happens

--Filip
0
 
LVL 8

Expert Comment

by:Exceter
ID: 8058646
xyzzer, press the Reload Question Button which is located at the top left of this page after posting. Otherwise refreshing the page will generate a duplicate post, this is also why the board gets flooded by duplicate questiosn from time to time.

Exceter
0
 

Author Comment

by:packman25
ID: 8058653
Thanks for the quick responses guys, it is working now.  If it was up to me i would have used a string instead.
0
 
LVL 8

Expert Comment

by:Exceter
ID: 8058683
You are most welcome.
0
 
LVL 2

Expert Comment

by:xyzzer
ID: 8058694
Sorry for that doubled message. I'm experiencing problems refreshing the page.
Thanks for that note about two staged usage of FormatMessage.
It's a function a use for our company's application in many places, so it might be useful to correct it.
Know any drawbacks of using LocalAlloc in such conditions?

--Filip
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question