質問

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