문제

I want to take all the content of a file in one go and put it in a "big string".. I dont want to put line by line. Is there any function to do that?

i want something like this:

int main(int argc, char *argv[]) {
    FILE *script;
        int i;
        char *code;

        if (argc > 1){
          for (i = 1; i < argc; i++){
            if ((script = fopen(argv[i], "r")) == NULL){
            perror(argv[i]);
            }else {
               code = malloc (sizeof(char)*sizeof(script));

               **HERE TAKE THE CONTENT AND PUT IN "CODE" IN ONE GO** 


             }
           }
         }
     printf("%s",code);
     fclose(script);
     free(codigo);
     exit(0);
}

Is that posible?

도움이 되었습니까?

해결책

you might also look into using

fseek(script, 0, SEEK_END); // position to the end of the file

size = ftell(script); // get the file size

fseek(script, 0, SEEK_SET); // rewind to the beginning of the file

code = malloc(sizeof(char)*(size+1));

if(code) { 
    fread(code, sizeof(char), size, script);
    code[size] = '\0';
}

with some additional error checking

다른 팁

Yes. Read up on ftell or stat to work on getting the size of the file to find out how much space you need to alloc (you can't use sizeof on a FILE * to get that info, it won't do what you think), and fread to read it in one go.

Sample code to use stat() to get the size:

#include <sys/stat.h>

off_t fsize(const char *fname) {
    struct stat st;

    if (stat(fname, &st) == 0)
        return st.st_size;

    return -1; 
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top