Jump to content

Reading a string from a text file?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
MoonBoots89

MoonBoots89

    Newbie

  • Members
  • Pip
  • 3 posts
Beginner here :blushing:

I've been asked to design a simple program in C that can open a text file, write to it and then display the text. I'm nearly there but I can't seem to `printf` the contents of the file.

Heres what I've got so far:

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

 

int main(int argc, char *argv[])

{

    FILE *fp;

    size_t count;

    char const *str = "This is text";

    fp = fopen("sample.txt", "wb");

    if(fp == NULL) {

        perror("Unable to open file");

        return EXIT_FAILURE;

    }

    count = fwrite(str, strlen(str), 1, fp);

    int fclose(FILE *fp);

    fp = fopen("sample.txt", "rb");

    printf("Here are the contents of the file: %s", fp);

    getchar();

    return 0;

}

It just comes up with `Here are the contents of the file:` and an empty space...any help would be much appreciated :)

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
You need to read the contents of the file into a buffer, and output the buffer with printf. Use fscanf to read from the file.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,714 posts
This is the simple way of doing it. I fixed a few bugs in your code.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
int main(int argc, char *argv[])
{
    FILE *fp;
    size_t count;
    //This is syntactically correct, but wrong for your purpose.
    //Replace this --> char const *str = "This is text";
    //With this:
    const char *str = "This is text";
    fp = fopen("sample.txt", "wb");
    if(fp == NULL) {
        perror("Unable to open file");
        return EXIT_FAILURE;
    }
    count = fwrite(str, strlen(str), 1, fp);
    //NO! This is the declaration for the function,
    //not the call you need to make. --> int fclose(FILE *fp);
    fclose(fp);  //This is how you do it.
    fp = fopen("sample.txt", "rb");
    //loop while there are still chars in the file and print each out.
    while(!feof(fp))
        printf("%c",(char)getc(fp));

    getchar();
    return 0;
}


#4
MoonBoots89

MoonBoots89

    Newbie

  • Members
  • Pip
  • 3 posts
Thanks! Its the first time that I've used most of these functions and I was getting really muddled up with the syntax - very frustrating!

Thanks again for the help.

:)