0

I want to save the contents of a .txt file into an array. The thing here is I am using the location first into another array and I want to use that array holding my location to store the contents of the file into an array. The code doesn't seem to work. Help appreciated.

#include <stdio.h>
#include <string.h>
int main()
{
   char location[50],input[1000]={0};
   int i=0; 
   printf("Enter your file location:\n");
   scanf("%999[^\n]",location);

   FILE *ptr;
   ptr = fopen("location", "r");

   while(!EOF)
   {
     char c;
     c = (char) fgetc(ptr);
     input[i] = c;
     printf("%c", input[i]);
     i++;
   }
   input[i] = NULL;
   printf("%s",input);
   getch();
   return 0;
}
Alexej Magura
  • 4,833
  • 3
  • 26
  • 40
Sahir
  • 329
  • 1
  • 2
  • 9
  • 5
    `fopen("location","r");` - sure you want `"location"` rather than `location`? – Mat Dec 24 '13 at 19:34

3 Answers3

2

EOF is something different (it's a macro, and thus !EOF is always a constant value, and doesn't actually check anything). Perhaps you meant to use feof(). Or, rather:

int c;
while ((c = fgetc(ptr)) != EOF)
{
    ...
Community
  • 1
  • 1
Cornstalks
  • 37,137
  • 18
  • 79
  • 144
2

Multiple problems

  1. Wrong size in scanf() for buffer and result should be tested.

    char location[50];
    // scanf("%999[^\n]",location);
    if (1 != scanf("%49[^\n]",location)) HandleError();
    
  2. Wrong parameter to fopen() (@Mat). Add test

    // ptr = fopen("location", "r");
    ptr = fopen(location, "r");
    if (ptr == NULL) HandleOpenError();
    
  3. Wrong use of EOF and c type (@Cornstalks)

    // while(!EOF) {
    //  char c;
    // c = (char) fgetc(ptr);
    int c;
    while ((c = fgetc(ptr)) != EOF) {
    
  4. Wrong termination.

    // input[i] = NULL;
    input[i] = '\0';
    
  5. UB if file length >= 1000;
    Check @Fiddling Bits answer for allocating a buffer for whole file.
    Suggest size_t fileLength instead of long int fileLength.
    Add free(pFileContents);

  6. No fclose()

     fclose(ptr);
     return 0;
    
  7. Minor: printf("%s",input); will not print out the entire file if text file is unusual and has embedded \0.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

First, you must determine the length of the file:

fseek(ptr, 0, SEEK_END);
long int fileLength = ftell(ptr);

Then, create an buffer large enough to hold the full contents of the file:

char *pFileContents = malloc(fileLength);
if(!pFileContents)
    return -1; // Error

Lastly, copy the contents of the file to the newly created buffer:

rewind(ptr);
if(fread(pFileContents, 1, fileLength, ptr) != fileLength)
    return -1; // Error
fclose(ptr);
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46