Read the entire contents of a file to c char *, including new lines

后端 未结 4 1889
孤城傲影
孤城傲影 2021-01-25 13:53

I\'m looking for a cross platform (Windows + Linux) solution to reading the contents of an entire file into a char *.

This is what I\'ve got now:



        
4条回答
  •  再見小時候
    2021-01-25 14:06

    Something like this, may be?

    FILE *stream;
    char *contents;
    fileSize = 0;
    
    //Open the stream. Note "b" to avoid DOS/UNIX new line conversion.
    stream = fopen(argv[1], "rb");
    
    //Seek to the end of the file to determine the file size
    fseek(stream, 0L, SEEK_END);
    fileSize = ftell(stream);
    fseek(stream, 0L, SEEK_SET);
    
    //Allocate enough memory (add 1 for the \0, since fread won't add it)
    contents = malloc(fileSize+1);
    
    //Read the file 
    size_t size=fread(contents,1,fileSize,stream);
    contents[size]=0; // Add terminating zero.
    
    //Print it again for debugging
    printf("Read %s\n", contents);
    
    //Close the file
    fclose(stream);
    free(contents);
    

提交回复
热议问题