Thread: Help with reading from a text file

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    116

    Help with reading from a text file

    Hi everyone

    I need to write some code for an assignment, that involves reading from a text file using C.

    I've tried to read through previous discussions but am really struggling to understand them. I'm not very strong in programming so wondered if anyone with some patience is able to give me a very simple explanation as to how to do this?

    I have created a text file that looks like this:

    0 12
    1 24
    2 34
    3 55
    etc...

    and ive instructed my programming to general 10 numbers randomly.

    What I need to know, is how to I then take those 10 random numbers, and find their corresponding number in the text file, and then give the corresponding number back.

    The 10 Randomly Generated Number's are in an array, so I need a second array with the corresponding values (e.g. if the first 3 randomly generated numbers were 2, 2, 0 then the corresponding numbers would be 34, 34, 12).

    I'm really struggling on how to access the text file, take and maniupulate the data and then input it into my new array. once im able to do this, im able to do the rest, so any advice or input will be greatly appreciated. please note i can only use C, not C++ and I'm not a programmer, Im studying Electrical and Electronic Engineering so need to have a basic grasp of C programming only, so am unable to follow complicated discussions and articles.

    Thank you in advance for your help

    all the best

  2. #2
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    So, have you even tried to experiment with the C file opening/reading commands at all?

    Google them. Try them. See what you can read in from the file. Then you'll know how to start on the next step.

    I'm really struggling on how to access the text file, take and maniupulate the data and then input it into my new array. once im able to do this, im able to do the rest
    Oh, I had to laugh at this. "The rest" being a for loop and an ==, presumably?

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    Yes I have been trying to experiment with them, with little success.

    And its a big assignment so involves quite a lot more but im reasonably comfortable with the rest of the things we have been taught apart from file access.

    Lastly, perhaps you might lose the arrogant tone. I purposely kept the opening post as polite as possible as I know how "Gangsta" keyboard warriors think they are when they are posting anonymously behind a screen (perhaps those same individuals were the ones getting bullied at school?) and I didnt want to give anyone any excuses to be rude or childish but it seems there is no real way to avoid this when posting in forums apart from the people your posting with actually growing up.

    So either post politely or dont post.



    rant over
    Last edited by Fordy; 04-26-2012 at 10:16 AM. Reason: Took out final insult

  4. #4
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    David_Baratheon, can you read data from the keyboard? As in are you familiar with basic scanf/printf I/O?
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  5. #5
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    hi claudiu, thanks for your response

    Ive had to do a number of assignments before this and am comfortable with printf, scanf, do, for and do while loops, functions, pointers, randomly generated numbers and other basic things. its only really the accessing and manipulating of data from a text file that im struggling with.

    hopefully hear from you soon

  6. #6
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Well you will be pleased to find that there is an equivalent to scanf and printf for file i/o, they are unimaginatively called fscanf and fprintf.

    Code:
    //open file for reading
    float a,b,c;
    FILE* inputFile = fopen("C:\inputfile.txt","r");
    fscanf(inputFile,"%f %f %f",&a,&b,&c);
    //close input file
    fclose(inputFile);
    
    //Open output file for writing
    FILE *outputFile = fopen("C:\outputfile.txt","w");
    fprintf(outputFile,"%f %f %f",a,b,c);
    //close output file
    fclose(outputFile);
    That's really all there is to it. If you want to read in strings you can use fgets(). You can Google that and find a ton of usage examples.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  7. #7
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    ok great thank you. Ill give it a go and if its ok ill post up again if i get stuck

    btw sorry ledow i just get so irritated at why there is always so much aggression and rudeness in forums. doesnt excuse me behaving the same way so i apologise

  8. #8
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    Quote Originally Posted by David_Baratheon View Post
    Yes I have been trying to experiment with them, with little success.
    Then would you like to share your code, as is normal practice on these forums for anyone who posts without code (read FAQ's or look at ANY post that doesn't have code or at least a very precise description of the exact point that someone starts to struggle, using including function names and errors / incorrect output they are getting). What exactly have you tried? Have you read through a file line by line and printed each out? Have you buffered a file into char arrays? Have you ever touched the direct operations (e.g. fscanf, fprintf, etc.)?

    It's not snarkiness - All you've said is "I don't know how to do it" followed by (now) "yeah, tried it, didn't work" which is infinitely less useful than my response trying to gauge what you've done and whether you've taken the simple step of Googling for C file access tutorials or whether, like a lot of posters here, you expect us to do your homework for you. I'm not saying that's the case here, but without knowing what you've tried and where you got to and what problems you HAD with what functions and methods, how do we even begin to tell you without either a) telling you to Google it (which I and another poster have done now) or b) doing it for you at great personal expense to ourselves?

    If you cannot take criticism and show effort from your side, you have to remember that you're expecting complete strangers with no incentive to help you (no matter how polite you are) beyond their own good will to take the time to work you through what you've done and gently mould you in the direction of an answer for your problem. "I dont' know what to do, tried stuff, didn't work" isn't useful, or confidence-inspiring, there at all.

    Show us what you've done. Tell us what you've tried. Tell us what didn't work and why you think that was. Tell us how you've broken the problem down, how you intend to approach it, what functions you want to use and how. Help stop us running in circles guessing, because it's just a lot easier for us to move to other topics where people with lesser problems but more effort (code, descriptions, Googling for themselves, etc.) are waiting for help on things they still struggle with.

    I dont have time for rude impolite little ******'s
    Snap.



    P.S. Apology noticed after I'd posted, and accepted, and I *can* be rude at times but I can get much more rude when people don't help themselves too.
    Last edited by ledow; 04-24-2012 at 10:02 AM.

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  9. #9
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    ok ledow your advice has been noted and I will try to post more info on what ive tried, need to do etc.

    But I did try googling it and also read some articles here and I either found them over complicated, or sometimes involving c++ code, and I really needed someone to explain to me how they work in very non programmer friendly terms. I guess the only way in which I can give back to the community in return is to help other newbie's who are in the same boat once im more experienced in programming.

    I'll give it a go and write some code using claudiu's suggestions and explanations and then maybe some constructive criticism of my coding and where im going wrong, where my misunderstandings etc will be useful if anyone has the time to respond

    thanks and all the best

  10. #10
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    One minor correction to what I previously typed in:

    the file paths should contain double '\' to avoid having the function interpret the next character as some escape symbol (for example \n).

    So make sure you write static paths as: "C:\\temp.txt" as opposed to "C:\temp.txt" in fopen()
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  11. #11
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    ok hopefully a worded explanation of my problem might be sufficient? As its an assignment so I would prefer to avoid posting it up here as I could run the risk of a plagurism panel at university if I dont just seek general advice on how to do certain things (this was my tutors advice when I asked concerning enquiring in forums related to assignments)

    what i essentially need to do is with a text file that contains text like this:

    0 12
    1 24
    2 34
    3 55


    get my program to look up numbers in the text file and find their equivilent in the text file and return it into an array.

    So presumably the first thing id need to do is open the text file:

    //open file for reading
    FILE* inputFile = fopen("textfile.txt","r");

    // manipulate tex file here

    fclose(inputFile);


    so how do I get the program to return values that correlate to the numbers I have. E.g. from the example I gave earlier:

    0 12
    1 24
    2 34
    3 55

    if i have two numbers, 1 and 3, how do I get the code to look at the text file and look at 1 and 3 and find out that the numbers are 24 and 55 and then return these two values in an array?

    Hopefully thats specific enough, at least if you know some simple commands that will point me in the right direction that would be great

    can I achieve this with fscanf?

    Also does fprintf write information to the text file and fscanf read data from the textfile?

  12. #12
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    There are several ways to go about this.

    The easiest way is to have two arrays of type int, or whatever type you are reading in from the file. Read the whole file, put the numbers from the first column in the file in array 1 called something like "key" and numbers from the second column in the second array called something like "values". Then when the user types in a "key", you look through the key array until you find it and remember the index you found it at. The value will reside in the values array at the same index.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  13. #13
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    You can read your two numbers in one line of fscanf given the fact that your input is formatted.

    fscanf(inputFile,"%d %d",keys[i],values[i]);
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  14. #14
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    ok thanks for all your help claudiu

    Ive just come from a programming class and from what i understand, the first thing I need to do is copy all of the data from the textfile and into arrays in my program and the data maipulation comes after that. So the first thing I need is 2 sets of 1 dimensional arrays called column1 (an integer) and column2 (a float). Ive declared these and have tried to transfer the data from the text file into my two arrays, but unfortunately its not currently working. Here is that section of my code:

    Code:
    FILE *fp;
    fp = fopen("C:\\TEMP\\LOOKUP.txt", "r");
    for(loop=0; loop<10; loop++)
    {
    fscanf(fp, "%i %f",&column1, &column2);
    printf("\n %i = %i", column1[loop], column2[loop]);
    }
    fclose(fp);
    
    


    what do you guys think? Can you see any clear errors in the code?

  15. #15
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Well a first clear error is that you are printing column2[loop] with specifier %i which is used for ints, but you are reading the data in as %f (float).
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 05-05-2010, 02:43 PM
  2. Reading from a text file
    By stevedawg85 in forum C++ Programming
    Replies: 8
    Last Post: 04-20-2006, 09:27 PM
  3. reading from text file
    By requiem in forum C++ Programming
    Replies: 1
    Last Post: 04-25-2003, 12:42 AM
  4. Reading from a text file....
    By Shadow in forum C Programming
    Replies: 5
    Last Post: 10-20-2001, 10:50 AM
  5. Reading text out of a file
    By Twiggy in forum C Programming
    Replies: 1
    Last Post: 10-17-2001, 11:17 AM