Return File Contents as String

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • NecNecco
    New Member
    • Oct 2014
    • 1

    Return File Contents as String

    Hello,

    I am completely new to C programming. Below code is that I gathered from Google searches and maybe incorrect.

    I am trying to code a function which will read a file on system and return its content back as string. Code is below.

    Code:
    char * readtxt(){
        FILE * fptr;
        char  c;
        static char txt[30];
        int len=0;
    
        fptr = fopen("C:\\Users\\Test\\Desktop\\Dev\\test.txt", "r");
        
        while(1){
            c = fgetc(fptr);
            if(c!= EOF) {
                txt[len]=c;
                len++;
            }
            else
                break;
        }
        fclose(fptr);  
    
        return txt;  
    }
    I suppose txt variable is pointer. But I need to return the file content as string so the function structure should look like

    Code:
    returnType function(){
    return "File Contents as String";
    }
    How can I achieve this please?

    Cheers
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I presume this is a text file and not a binary file. That is, you can read the data in a text editor like notepad.exe or vi? Yes?

    Assuming that's correct then you want to read data until you reach a newline character (\n). You can do this a character at a time as in your code but you can also use the system's fgets function to read the data into a char array. This function will read characters until is reaches the \n which is changed to \0 to provide the null terminator for the string.

    Code:
    fgets(txt, 30, fptr);
    and you are done.

    Note that the source code for all C library functions is available online so you can see how fgets works.

    If you have to read character-by-character as a class exercise, then use the loop you have but stop when you see the \n, change the character to \0, append it to your buffer, and stop the loop.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Are you sure that every line in the input file will fit in a 30-entry array? Don't forget to take into account the extra character (null terminator) added by fgets.

      If you read character-by-character then the code in the loop also has to protect against writing past the end of the txt array. You should have explicit protection to keep from writing past the end of the array even if you are certain the input file is always small enough to fit.

      Comment

      Working...