Thread: Simple read from TXT

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    162

    Simple read from TXT

    Hi,

    I cant find an error in this code... Its supposed to read simple txt file.

    Code:
    #include <iostream>
    #include <stdio.h>
    
    int end;
    int size;
    FILE *file;
    char *buffer;
    char *read;
    
    void Open()
    {
        if((file = fopen("text.txt", "r+")) == NULL)
        {
                printf("File not found\n");
        }
        else
        {
                printf("File has been opened\n");
        }
    }
    
    void Read()
    {
         if(fread(read, size, 1, file))
         {
                         std::cout << "Read from file: \n\t" << read << "\n";
         }
         else
         {
                        printf("Failed to read from file\n");
         }
    }
    
    void Close()
    {
        if(fclose(file))
        {
                              printf("File can not be closed\n");
        }
        else
        {
                              printf("File closed\n");
        }
    }
    
    int main(void)
    {
        Open();
        Read();
        Close();
        std::cin >> end;
    }
    Can you help me out please? The app never reads the content or crashes right away

    [Dev-C++]

  2. #2
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    - initialize your variables
    - reserve memory to hold read values
    - use RAII (encapsulate your parameters and functions open, read, close in a class)

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> char *read;

    a pointer alone allocates no storage. use malloc or a local buffer. or better yet use a real container like std::string or std::vector. and remember that uninitialized pointers are very dangerous since they cause code to crash at unpredictable times...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    remember that uninitialized pointers are very dangerous since they cause code to crash at unpredictable times...
    Not necessarily -- uninitialized pointers by themselves can do no harm. It's just when you try to dereference them that things can go wrong. This program, for example, never crashes. (Unless your compiler or environment is seriously messed up.)
    Code:
    #include <string.h>
    
    int main() {
        char str[10];
        char *uninitialized;
        char *p;
    
        p = str;
        strcpy(p, "data");
    
        return 0;
    }
    A suggestion: don't use global variables if you can help it. Passing stuff around between functions might seem more laborious, but it's a much better habit to have in the long run.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Don't teach newbies very bad practices! This is a very big ticking time bomb!
    Never copy data into an unallocated space.
    Just defining a pointer somewhere does not allocate memory.
    And this is all C, but the end std::cin. Use proper C++ if you really want to use it. C++ isn't C, as C++ can do wonderful stuff C cannot, and it is obvious you should take advantage of it.
    As has already been suggested, use a std::vector or std::string for buffer and read using file streams.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by Elysia View Post
    Don't teach newbies very bad practices! This is a very big ticking time bomb!
    Never copy data into an unallocated space.
    Umm . . . I didn't. I declared an uninitialized pointer, then later set it to point to a buffer of ten characters, and then copied something into that buffer via the pointer. It was meant to show that an uninitialized pointer does not affect how it can be used later on.
    Just defining a pointer somewhere does not allocate memory.
    This is true. I never said otherwise. I was debating the point that any uninitialized pointer could cause the program to crash at any time.
    And this is all C, but the end std::cin. Use proper C++ if you really want to use it. C++ isn't C, as C++ can do wonderful stuff C cannot, and it is obvious you should take advantage of it.
    Yes, it is. That's why I carefully wrote a sample program that is valid C and C++.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> uninitialized pointers by themselves can do no harm. It's just when you try to dereference them that things can go wrong.

    precisely my point. initialized pointers are that much easier to debug!

    >> C++ isn't C, as C++ can do wonderful stuff C cannot, and it is obvious you should take advantage of it.

    perhaps less obvious is that some of us don't make as much of a distinction. it is foolish not to take advantage the STL, of course (especially as a beginner), but you do still have to learn the core parts of the language too, eventually.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    >> uninitialized pointers by themselves can do no harm. It's just when you try to dereference them that things can go wrong.

    precisely my point. initialized pointers are that much easier to debug!
    I didn't mean to suggest that having pointers that are only initialized later in the code with some convoluted logic that is very hard to follow is a good thing. I was just contesting this statement:
    remember that uninitialized pointers are very dangerous since they cause code to crash at unpredictable times...
    The fact is, uninitialized pointers do not "cause code to crash". They can cause code to crash. Adding "char *uninitialized_pointer;" to your code is not going to cause it to crash. In addition, writing to an uninitialized pointer is not guaranteed to crash your program -- although that outcome is very likely. It's simply undefined behaviour.

    You can tell I'm a programmer with such stubborn emphasis on being "correct".

    Anyway, it's not important. I think we both know what we're talking about, and we're probably just confusing the OP -- especially me.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Registered User
    Join Date
    Apr 2007
    Posts
    162
    Thanks everyone for help... Have solved it now

    For record:

    Code:
    char read[1024];
    FILE *file;
    
    void Open()
    {
        if((file = fopen("text.txt", "r+")) == NULL)
        {
                printf("File not found\n");
        }
        else
        {
                printf("File has been opened\n");
        }
    }
    
    void Read(int lenght)
    {
         for(int i = 0; i <= lenght; i++)
         {
                 read[i] = getc(file);
         }
         if(read)
         {
                         std::cout << "Read from file: \n\n\t" << read << "\n";
         }
         else
         {
                        printf("Failed to read from file\n");
         }
    }

  10. #10
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    So if you fail to open the file, you're still going to try to read and then close it? As soon as that fails, you should do something about it. (Although this usually means spitting out an error messaging and crapping out)

    Don't use a variable name like lenght. Change it to length.
    Normally, you should not access read[length]. The highest one should be read[length-1] unless length is not what is normally meant by length.

    If you're going to use C, use C. Otherwise use C++. I'm assuming you want C++, so us fstream for file i/o.




    And clean up your tabs before the indentation police (Elysia) get after you.
    Last edited by NeonBlack; 03-02-2008 at 01:21 PM.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 19
    Last Post: 06-16-2008, 05:00 AM
  2. Weird read input or bad printf output?
    By ChaoticMachiner in forum C Programming
    Replies: 3
    Last Post: 05-04-2008, 03:40 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Help! Can't read decimal number
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 09-07-2001, 02:09 AM
  5. Simple File Creation Algorithm
    By muffin in forum C Programming
    Replies: 13
    Last Post: 08-24-2001, 03:28 PM