Tried to call text file and copy the text file to my new variable in C programming





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-2















my text file is "Foo bar!!", name foo.txt



So i want to create a new variable in my main function and copy the text file into new variable.



#include <stdio.h>
#include <stdlib.h>

FILE *fopen_with_error (const char *f, const char *mode){
FILE *fp;
if((fp = fopen(f,mode)) == NULL){
printf("Error opening %sn",f);
exit(EXIT_FAILURE);
}
return fp;
}

int main(int argc, char* argv){

FILE *fp;
int a, num;
if(argc != 2){
printf("Usage: program input filen");
return 0;
}
fp = fopen_with_error(argv[1],"rb");
}


I want to store the copied text into 'a' variable.



I tried to use fread function but everytime i try, it fails somehow.










share|improve this question




















  • 4





    where do you use fread? its not in the source you posted.

    – Bwebb
    Nov 26 '18 at 22:31






  • 2





    The text "Foo bar!!" is not an integer, and therefore it makes no sense to store it in variable a.

    – user3386109
    Nov 26 '18 at 22:31











  • It looks like the FILE * youre returning is going out of scope too, probably want that in main and pass it by reference. I dont see the a assignment above and i still dont see fread in your code

    – Bwebb
    Nov 26 '18 at 22:35






  • 2





    @Bwebb no it's not -- it's being returned from fopen_with_error and stored in the variable fp in main. But all the other comments still apply -- nothing is actually being read, and an integer is not an appropriate datatype for storing strings.

    – paddy
    Nov 26 '18 at 23:05











  • regarding: printf("Error opening %sn",f); 1) Error messages should be output to stderr, not stdout. 2) when the error indication is from a C library function, should also output the text reason the system thinks the error occurred. Suggest: perror( "fopen failed" );

    – user3629249
    Nov 26 '18 at 23:11


















-2















my text file is "Foo bar!!", name foo.txt



So i want to create a new variable in my main function and copy the text file into new variable.



#include <stdio.h>
#include <stdlib.h>

FILE *fopen_with_error (const char *f, const char *mode){
FILE *fp;
if((fp = fopen(f,mode)) == NULL){
printf("Error opening %sn",f);
exit(EXIT_FAILURE);
}
return fp;
}

int main(int argc, char* argv){

FILE *fp;
int a, num;
if(argc != 2){
printf("Usage: program input filen");
return 0;
}
fp = fopen_with_error(argv[1],"rb");
}


I want to store the copied text into 'a' variable.



I tried to use fread function but everytime i try, it fails somehow.










share|improve this question




















  • 4





    where do you use fread? its not in the source you posted.

    – Bwebb
    Nov 26 '18 at 22:31






  • 2





    The text "Foo bar!!" is not an integer, and therefore it makes no sense to store it in variable a.

    – user3386109
    Nov 26 '18 at 22:31











  • It looks like the FILE * youre returning is going out of scope too, probably want that in main and pass it by reference. I dont see the a assignment above and i still dont see fread in your code

    – Bwebb
    Nov 26 '18 at 22:35






  • 2





    @Bwebb no it's not -- it's being returned from fopen_with_error and stored in the variable fp in main. But all the other comments still apply -- nothing is actually being read, and an integer is not an appropriate datatype for storing strings.

    – paddy
    Nov 26 '18 at 23:05











  • regarding: printf("Error opening %sn",f); 1) Error messages should be output to stderr, not stdout. 2) when the error indication is from a C library function, should also output the text reason the system thinks the error occurred. Suggest: perror( "fopen failed" );

    – user3629249
    Nov 26 '18 at 23:11














-2












-2








-2


1






my text file is "Foo bar!!", name foo.txt



So i want to create a new variable in my main function and copy the text file into new variable.



#include <stdio.h>
#include <stdlib.h>

FILE *fopen_with_error (const char *f, const char *mode){
FILE *fp;
if((fp = fopen(f,mode)) == NULL){
printf("Error opening %sn",f);
exit(EXIT_FAILURE);
}
return fp;
}

int main(int argc, char* argv){

FILE *fp;
int a, num;
if(argc != 2){
printf("Usage: program input filen");
return 0;
}
fp = fopen_with_error(argv[1],"rb");
}


I want to store the copied text into 'a' variable.



I tried to use fread function but everytime i try, it fails somehow.










share|improve this question
















my text file is "Foo bar!!", name foo.txt



So i want to create a new variable in my main function and copy the text file into new variable.



#include <stdio.h>
#include <stdlib.h>

FILE *fopen_with_error (const char *f, const char *mode){
FILE *fp;
if((fp = fopen(f,mode)) == NULL){
printf("Error opening %sn",f);
exit(EXIT_FAILURE);
}
return fp;
}

int main(int argc, char* argv){

FILE *fp;
int a, num;
if(argc != 2){
printf("Usage: program input filen");
return 0;
}
fp = fopen_with_error(argv[1],"rb");
}


I want to store the copied text into 'a' variable.



I tried to use fread function but everytime i try, it fails somehow.







c






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 23:59









David C. Rankin

43.7k33252




43.7k33252










asked Nov 26 '18 at 22:28









ANDYANDY

1




1








  • 4





    where do you use fread? its not in the source you posted.

    – Bwebb
    Nov 26 '18 at 22:31






  • 2





    The text "Foo bar!!" is not an integer, and therefore it makes no sense to store it in variable a.

    – user3386109
    Nov 26 '18 at 22:31











  • It looks like the FILE * youre returning is going out of scope too, probably want that in main and pass it by reference. I dont see the a assignment above and i still dont see fread in your code

    – Bwebb
    Nov 26 '18 at 22:35






  • 2





    @Bwebb no it's not -- it's being returned from fopen_with_error and stored in the variable fp in main. But all the other comments still apply -- nothing is actually being read, and an integer is not an appropriate datatype for storing strings.

    – paddy
    Nov 26 '18 at 23:05











  • regarding: printf("Error opening %sn",f); 1) Error messages should be output to stderr, not stdout. 2) when the error indication is from a C library function, should also output the text reason the system thinks the error occurred. Suggest: perror( "fopen failed" );

    – user3629249
    Nov 26 '18 at 23:11














  • 4





    where do you use fread? its not in the source you posted.

    – Bwebb
    Nov 26 '18 at 22:31






  • 2





    The text "Foo bar!!" is not an integer, and therefore it makes no sense to store it in variable a.

    – user3386109
    Nov 26 '18 at 22:31











  • It looks like the FILE * youre returning is going out of scope too, probably want that in main and pass it by reference. I dont see the a assignment above and i still dont see fread in your code

    – Bwebb
    Nov 26 '18 at 22:35






  • 2





    @Bwebb no it's not -- it's being returned from fopen_with_error and stored in the variable fp in main. But all the other comments still apply -- nothing is actually being read, and an integer is not an appropriate datatype for storing strings.

    – paddy
    Nov 26 '18 at 23:05











  • regarding: printf("Error opening %sn",f); 1) Error messages should be output to stderr, not stdout. 2) when the error indication is from a C library function, should also output the text reason the system thinks the error occurred. Suggest: perror( "fopen failed" );

    – user3629249
    Nov 26 '18 at 23:11








4




4





where do you use fread? its not in the source you posted.

– Bwebb
Nov 26 '18 at 22:31





where do you use fread? its not in the source you posted.

– Bwebb
Nov 26 '18 at 22:31




2




2





The text "Foo bar!!" is not an integer, and therefore it makes no sense to store it in variable a.

– user3386109
Nov 26 '18 at 22:31





The text "Foo bar!!" is not an integer, and therefore it makes no sense to store it in variable a.

– user3386109
Nov 26 '18 at 22:31













It looks like the FILE * youre returning is going out of scope too, probably want that in main and pass it by reference. I dont see the a assignment above and i still dont see fread in your code

– Bwebb
Nov 26 '18 at 22:35





It looks like the FILE * youre returning is going out of scope too, probably want that in main and pass it by reference. I dont see the a assignment above and i still dont see fread in your code

– Bwebb
Nov 26 '18 at 22:35




2




2





@Bwebb no it's not -- it's being returned from fopen_with_error and stored in the variable fp in main. But all the other comments still apply -- nothing is actually being read, and an integer is not an appropriate datatype for storing strings.

– paddy
Nov 26 '18 at 23:05





@Bwebb no it's not -- it's being returned from fopen_with_error and stored in the variable fp in main. But all the other comments still apply -- nothing is actually being read, and an integer is not an appropriate datatype for storing strings.

– paddy
Nov 26 '18 at 23:05













regarding: printf("Error opening %sn",f); 1) Error messages should be output to stderr, not stdout. 2) when the error indication is from a C library function, should also output the text reason the system thinks the error occurred. Suggest: perror( "fopen failed" );

– user3629249
Nov 26 '18 at 23:11





regarding: printf("Error opening %sn",f); 1) Error messages should be output to stderr, not stdout. 2) when the error indication is from a C library function, should also output the text reason the system thinks the error occurred. Suggest: perror( "fopen failed" );

– user3629249
Nov 26 '18 at 23:11












2 Answers
2






active

oldest

votes


















1














In addition to using stat to obtain the number of bytes in the file to accurately size your buffer for reading the file into a single variable, you can also use fseek and ftell to accomplish the same thing.



The bigger issue is that you post the contents of a text file with a single-line (e.g. "Foo bar!!") and then proceed to explain you want to read the entire file into a variable. For binary input, that makes more sense. For text, you generally want to read and store individual lines rather than a file-at-once.



(you can store an entire text file line-by-line by using a pointer to pointer to char and allocating pointer and then storage for each line)



Now, don't get me wrong, you can do either, but if you need specific information from each line, and the lines differ in length, etc.., it is a whole lot easier to iterate over pointers than it is trying to scan through one giant buffer of text picking out newlines. You can think through what you need to do with the data you read from the file and make the call.



As your question is written, the basic approach is simply to open the file in binary mode, fseek forward to the end of file, use ftell to report the number of bytes in the file, allocate/validate memory to hold the file, and then read the file using fread into the allocated block of memory. (note: mmap provides another option as well)



Putting that pieces together, you could do something like the following:



#include <stdio.h>
#include <stdlib.h>

char *read_file (char* fname, size_t *nbytes)
{
long bytes = 0;
char* file_content;
FILE *file = fopen(fname, "rb");

if (!file) /* validate file open for reading */
return NULL;

fseek (file, 0, SEEK_END); /* fseek end of file */
if ((bytes = ftell (file)) == -1) { /* get number of bytes */
fprintf (stderr, "error: unable to determine file length.n");
return NULL;
}
fseek (file, 0, SEEK_SET); /* fseek beginning of file */

/* allocate memory for file */
if (!(file_content = malloc (bytes))) { /* allocate/validate memory */
perror ("malloc - virtual memory exhausted");
return NULL;
}

/* read all data into file in single call to fread */
if (fread (file_content, 1, (size_t)bytes, file) != (size_t)bytes) {
fprintf (stderr, "error: failed to read %ld-bytes from '%s'.n",
bytes, fname);
return NULL;
}
fclose (file); /* close file */
*nbytes = (size_t)bytes; /* update nbytes making size avialable */

return file_content; /* return pointer to caller */
}

int main (int argc, char **argv) {

size_t nbytes;
char *content;

if (argc < 2) { /* validate required argument givent */
fprintf (stderr, "error: insufficient input. filename req'd.n");
return 1;
}

if ((content = read_file (argv[1], &nbytes))) { /* read/validate */
printf ("read %zu bytes of data from %sn"
"------content------n%sn-------------------n",
nbytes, argv[1], content);
free (content);
}

return 0;
}


Example Input File



$ cat dat/foo.txt
"Foo bar!!"


Example Use/Output



$ ./bin/freadbinfoo dat/foo.txt
read 12 bytes of data from dat/foo.txt
------content------
"Foo bar!!"

-------------------


Don't forget to use a memory use & error checking program (like valgrind on Linux) to insure there are no memory errors and that you have freed all memory you have allocated.






share|improve this answer































    1














    Here's a simple example of how to do this:



    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    int main(int argc, char **argv) {
    char *fname = "./someFileNameHere";
    struct stat st;
    stat(fname, &st);
    char *content = malloc(st.st_size+1);
    content[st.st_size] = 0;
    FILE *infile = fopen(fname, "rb");
    size_t read = fread(content, sizeof(char), st.st_size, infile);
    fclose(infile);
    puts(content);
    return 0;
    }


    I've left all of the necessary error handling to you.






    share|improve this answer


























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53490082%2ftried-to-call-text-file-and-copy-the-text-file-to-my-new-variable-in-c-programmi%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      In addition to using stat to obtain the number of bytes in the file to accurately size your buffer for reading the file into a single variable, you can also use fseek and ftell to accomplish the same thing.



      The bigger issue is that you post the contents of a text file with a single-line (e.g. "Foo bar!!") and then proceed to explain you want to read the entire file into a variable. For binary input, that makes more sense. For text, you generally want to read and store individual lines rather than a file-at-once.



      (you can store an entire text file line-by-line by using a pointer to pointer to char and allocating pointer and then storage for each line)



      Now, don't get me wrong, you can do either, but if you need specific information from each line, and the lines differ in length, etc.., it is a whole lot easier to iterate over pointers than it is trying to scan through one giant buffer of text picking out newlines. You can think through what you need to do with the data you read from the file and make the call.



      As your question is written, the basic approach is simply to open the file in binary mode, fseek forward to the end of file, use ftell to report the number of bytes in the file, allocate/validate memory to hold the file, and then read the file using fread into the allocated block of memory. (note: mmap provides another option as well)



      Putting that pieces together, you could do something like the following:



      #include <stdio.h>
      #include <stdlib.h>

      char *read_file (char* fname, size_t *nbytes)
      {
      long bytes = 0;
      char* file_content;
      FILE *file = fopen(fname, "rb");

      if (!file) /* validate file open for reading */
      return NULL;

      fseek (file, 0, SEEK_END); /* fseek end of file */
      if ((bytes = ftell (file)) == -1) { /* get number of bytes */
      fprintf (stderr, "error: unable to determine file length.n");
      return NULL;
      }
      fseek (file, 0, SEEK_SET); /* fseek beginning of file */

      /* allocate memory for file */
      if (!(file_content = malloc (bytes))) { /* allocate/validate memory */
      perror ("malloc - virtual memory exhausted");
      return NULL;
      }

      /* read all data into file in single call to fread */
      if (fread (file_content, 1, (size_t)bytes, file) != (size_t)bytes) {
      fprintf (stderr, "error: failed to read %ld-bytes from '%s'.n",
      bytes, fname);
      return NULL;
      }
      fclose (file); /* close file */
      *nbytes = (size_t)bytes; /* update nbytes making size avialable */

      return file_content; /* return pointer to caller */
      }

      int main (int argc, char **argv) {

      size_t nbytes;
      char *content;

      if (argc < 2) { /* validate required argument givent */
      fprintf (stderr, "error: insufficient input. filename req'd.n");
      return 1;
      }

      if ((content = read_file (argv[1], &nbytes))) { /* read/validate */
      printf ("read %zu bytes of data from %sn"
      "------content------n%sn-------------------n",
      nbytes, argv[1], content);
      free (content);
      }

      return 0;
      }


      Example Input File



      $ cat dat/foo.txt
      "Foo bar!!"


      Example Use/Output



      $ ./bin/freadbinfoo dat/foo.txt
      read 12 bytes of data from dat/foo.txt
      ------content------
      "Foo bar!!"

      -------------------


      Don't forget to use a memory use & error checking program (like valgrind on Linux) to insure there are no memory errors and that you have freed all memory you have allocated.






      share|improve this answer




























        1














        In addition to using stat to obtain the number of bytes in the file to accurately size your buffer for reading the file into a single variable, you can also use fseek and ftell to accomplish the same thing.



        The bigger issue is that you post the contents of a text file with a single-line (e.g. "Foo bar!!") and then proceed to explain you want to read the entire file into a variable. For binary input, that makes more sense. For text, you generally want to read and store individual lines rather than a file-at-once.



        (you can store an entire text file line-by-line by using a pointer to pointer to char and allocating pointer and then storage for each line)



        Now, don't get me wrong, you can do either, but if you need specific information from each line, and the lines differ in length, etc.., it is a whole lot easier to iterate over pointers than it is trying to scan through one giant buffer of text picking out newlines. You can think through what you need to do with the data you read from the file and make the call.



        As your question is written, the basic approach is simply to open the file in binary mode, fseek forward to the end of file, use ftell to report the number of bytes in the file, allocate/validate memory to hold the file, and then read the file using fread into the allocated block of memory. (note: mmap provides another option as well)



        Putting that pieces together, you could do something like the following:



        #include <stdio.h>
        #include <stdlib.h>

        char *read_file (char* fname, size_t *nbytes)
        {
        long bytes = 0;
        char* file_content;
        FILE *file = fopen(fname, "rb");

        if (!file) /* validate file open for reading */
        return NULL;

        fseek (file, 0, SEEK_END); /* fseek end of file */
        if ((bytes = ftell (file)) == -1) { /* get number of bytes */
        fprintf (stderr, "error: unable to determine file length.n");
        return NULL;
        }
        fseek (file, 0, SEEK_SET); /* fseek beginning of file */

        /* allocate memory for file */
        if (!(file_content = malloc (bytes))) { /* allocate/validate memory */
        perror ("malloc - virtual memory exhausted");
        return NULL;
        }

        /* read all data into file in single call to fread */
        if (fread (file_content, 1, (size_t)bytes, file) != (size_t)bytes) {
        fprintf (stderr, "error: failed to read %ld-bytes from '%s'.n",
        bytes, fname);
        return NULL;
        }
        fclose (file); /* close file */
        *nbytes = (size_t)bytes; /* update nbytes making size avialable */

        return file_content; /* return pointer to caller */
        }

        int main (int argc, char **argv) {

        size_t nbytes;
        char *content;

        if (argc < 2) { /* validate required argument givent */
        fprintf (stderr, "error: insufficient input. filename req'd.n");
        return 1;
        }

        if ((content = read_file (argv[1], &nbytes))) { /* read/validate */
        printf ("read %zu bytes of data from %sn"
        "------content------n%sn-------------------n",
        nbytes, argv[1], content);
        free (content);
        }

        return 0;
        }


        Example Input File



        $ cat dat/foo.txt
        "Foo bar!!"


        Example Use/Output



        $ ./bin/freadbinfoo dat/foo.txt
        read 12 bytes of data from dat/foo.txt
        ------content------
        "Foo bar!!"

        -------------------


        Don't forget to use a memory use & error checking program (like valgrind on Linux) to insure there are no memory errors and that you have freed all memory you have allocated.






        share|improve this answer


























          1












          1








          1







          In addition to using stat to obtain the number of bytes in the file to accurately size your buffer for reading the file into a single variable, you can also use fseek and ftell to accomplish the same thing.



          The bigger issue is that you post the contents of a text file with a single-line (e.g. "Foo bar!!") and then proceed to explain you want to read the entire file into a variable. For binary input, that makes more sense. For text, you generally want to read and store individual lines rather than a file-at-once.



          (you can store an entire text file line-by-line by using a pointer to pointer to char and allocating pointer and then storage for each line)



          Now, don't get me wrong, you can do either, but if you need specific information from each line, and the lines differ in length, etc.., it is a whole lot easier to iterate over pointers than it is trying to scan through one giant buffer of text picking out newlines. You can think through what you need to do with the data you read from the file and make the call.



          As your question is written, the basic approach is simply to open the file in binary mode, fseek forward to the end of file, use ftell to report the number of bytes in the file, allocate/validate memory to hold the file, and then read the file using fread into the allocated block of memory. (note: mmap provides another option as well)



          Putting that pieces together, you could do something like the following:



          #include <stdio.h>
          #include <stdlib.h>

          char *read_file (char* fname, size_t *nbytes)
          {
          long bytes = 0;
          char* file_content;
          FILE *file = fopen(fname, "rb");

          if (!file) /* validate file open for reading */
          return NULL;

          fseek (file, 0, SEEK_END); /* fseek end of file */
          if ((bytes = ftell (file)) == -1) { /* get number of bytes */
          fprintf (stderr, "error: unable to determine file length.n");
          return NULL;
          }
          fseek (file, 0, SEEK_SET); /* fseek beginning of file */

          /* allocate memory for file */
          if (!(file_content = malloc (bytes))) { /* allocate/validate memory */
          perror ("malloc - virtual memory exhausted");
          return NULL;
          }

          /* read all data into file in single call to fread */
          if (fread (file_content, 1, (size_t)bytes, file) != (size_t)bytes) {
          fprintf (stderr, "error: failed to read %ld-bytes from '%s'.n",
          bytes, fname);
          return NULL;
          }
          fclose (file); /* close file */
          *nbytes = (size_t)bytes; /* update nbytes making size avialable */

          return file_content; /* return pointer to caller */
          }

          int main (int argc, char **argv) {

          size_t nbytes;
          char *content;

          if (argc < 2) { /* validate required argument givent */
          fprintf (stderr, "error: insufficient input. filename req'd.n");
          return 1;
          }

          if ((content = read_file (argv[1], &nbytes))) { /* read/validate */
          printf ("read %zu bytes of data from %sn"
          "------content------n%sn-------------------n",
          nbytes, argv[1], content);
          free (content);
          }

          return 0;
          }


          Example Input File



          $ cat dat/foo.txt
          "Foo bar!!"


          Example Use/Output



          $ ./bin/freadbinfoo dat/foo.txt
          read 12 bytes of data from dat/foo.txt
          ------content------
          "Foo bar!!"

          -------------------


          Don't forget to use a memory use & error checking program (like valgrind on Linux) to insure there are no memory errors and that you have freed all memory you have allocated.






          share|improve this answer













          In addition to using stat to obtain the number of bytes in the file to accurately size your buffer for reading the file into a single variable, you can also use fseek and ftell to accomplish the same thing.



          The bigger issue is that you post the contents of a text file with a single-line (e.g. "Foo bar!!") and then proceed to explain you want to read the entire file into a variable. For binary input, that makes more sense. For text, you generally want to read and store individual lines rather than a file-at-once.



          (you can store an entire text file line-by-line by using a pointer to pointer to char and allocating pointer and then storage for each line)



          Now, don't get me wrong, you can do either, but if you need specific information from each line, and the lines differ in length, etc.., it is a whole lot easier to iterate over pointers than it is trying to scan through one giant buffer of text picking out newlines. You can think through what you need to do with the data you read from the file and make the call.



          As your question is written, the basic approach is simply to open the file in binary mode, fseek forward to the end of file, use ftell to report the number of bytes in the file, allocate/validate memory to hold the file, and then read the file using fread into the allocated block of memory. (note: mmap provides another option as well)



          Putting that pieces together, you could do something like the following:



          #include <stdio.h>
          #include <stdlib.h>

          char *read_file (char* fname, size_t *nbytes)
          {
          long bytes = 0;
          char* file_content;
          FILE *file = fopen(fname, "rb");

          if (!file) /* validate file open for reading */
          return NULL;

          fseek (file, 0, SEEK_END); /* fseek end of file */
          if ((bytes = ftell (file)) == -1) { /* get number of bytes */
          fprintf (stderr, "error: unable to determine file length.n");
          return NULL;
          }
          fseek (file, 0, SEEK_SET); /* fseek beginning of file */

          /* allocate memory for file */
          if (!(file_content = malloc (bytes))) { /* allocate/validate memory */
          perror ("malloc - virtual memory exhausted");
          return NULL;
          }

          /* read all data into file in single call to fread */
          if (fread (file_content, 1, (size_t)bytes, file) != (size_t)bytes) {
          fprintf (stderr, "error: failed to read %ld-bytes from '%s'.n",
          bytes, fname);
          return NULL;
          }
          fclose (file); /* close file */
          *nbytes = (size_t)bytes; /* update nbytes making size avialable */

          return file_content; /* return pointer to caller */
          }

          int main (int argc, char **argv) {

          size_t nbytes;
          char *content;

          if (argc < 2) { /* validate required argument givent */
          fprintf (stderr, "error: insufficient input. filename req'd.n");
          return 1;
          }

          if ((content = read_file (argv[1], &nbytes))) { /* read/validate */
          printf ("read %zu bytes of data from %sn"
          "------content------n%sn-------------------n",
          nbytes, argv[1], content);
          free (content);
          }

          return 0;
          }


          Example Input File



          $ cat dat/foo.txt
          "Foo bar!!"


          Example Use/Output



          $ ./bin/freadbinfoo dat/foo.txt
          read 12 bytes of data from dat/foo.txt
          ------content------
          "Foo bar!!"

          -------------------


          Don't forget to use a memory use & error checking program (like valgrind on Linux) to insure there are no memory errors and that you have freed all memory you have allocated.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 27 '18 at 1:24









          David C. RankinDavid C. Rankin

          43.7k33252




          43.7k33252

























              1














              Here's a simple example of how to do this:



              #include <stdio.h>
              #include <stdlib.h>
              #include <sys/stat.h>
              int main(int argc, char **argv) {
              char *fname = "./someFileNameHere";
              struct stat st;
              stat(fname, &st);
              char *content = malloc(st.st_size+1);
              content[st.st_size] = 0;
              FILE *infile = fopen(fname, "rb");
              size_t read = fread(content, sizeof(char), st.st_size, infile);
              fclose(infile);
              puts(content);
              return 0;
              }


              I've left all of the necessary error handling to you.






              share|improve this answer






























                1














                Here's a simple example of how to do this:



                #include <stdio.h>
                #include <stdlib.h>
                #include <sys/stat.h>
                int main(int argc, char **argv) {
                char *fname = "./someFileNameHere";
                struct stat st;
                stat(fname, &st);
                char *content = malloc(st.st_size+1);
                content[st.st_size] = 0;
                FILE *infile = fopen(fname, "rb");
                size_t read = fread(content, sizeof(char), st.st_size, infile);
                fclose(infile);
                puts(content);
                return 0;
                }


                I've left all of the necessary error handling to you.






                share|improve this answer




























                  1












                  1








                  1







                  Here's a simple example of how to do this:



                  #include <stdio.h>
                  #include <stdlib.h>
                  #include <sys/stat.h>
                  int main(int argc, char **argv) {
                  char *fname = "./someFileNameHere";
                  struct stat st;
                  stat(fname, &st);
                  char *content = malloc(st.st_size+1);
                  content[st.st_size] = 0;
                  FILE *infile = fopen(fname, "rb");
                  size_t read = fread(content, sizeof(char), st.st_size, infile);
                  fclose(infile);
                  puts(content);
                  return 0;
                  }


                  I've left all of the necessary error handling to you.






                  share|improve this answer















                  Here's a simple example of how to do this:



                  #include <stdio.h>
                  #include <stdlib.h>
                  #include <sys/stat.h>
                  int main(int argc, char **argv) {
                  char *fname = "./someFileNameHere";
                  struct stat st;
                  stat(fname, &st);
                  char *content = malloc(st.st_size+1);
                  content[st.st_size] = 0;
                  FILE *infile = fopen(fname, "rb");
                  size_t read = fread(content, sizeof(char), st.st_size, infile);
                  fclose(infile);
                  puts(content);
                  return 0;
                  }


                  I've left all of the necessary error handling to you.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 27 '18 at 4:14

























                  answered Nov 26 '18 at 23:32









                  Tom DrakeTom Drake

                  43749




                  43749






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53490082%2ftried-to-call-text-file-and-copy-the-text-file-to-my-new-variable-in-c-programmi%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Tonle Sap (See)

                      I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                      Guatemaltekische Davis-Cup-Mannschaft