簡體   English   中英

用fprintf寫入文件

[英]write into a file with fprintf

我嘗試使用此功能寫入文件。 當我用這一行調用函數時,文件保持為空:

if(argc-optind==0){
  char* line=readcli();
  printf("testline:%s\n",line); //WORKS
  line=replacet(line,t,countt(line));
  if(oFlag==1){
    writeinfile(line,oFileName);
  }else{
    printf("Expanded:%s\n",line);
  }
}

但是,如果我這樣稱呼它,它將起作用:

char text[]={"test"};
char * textptr=text;
writeinfile(textptr,fp);

void writeinfile(char* line,char* file){
  FILE *f = fopen(file, "a");
  if (f == NULL){
    printf("Error opening file!\n");
    exit(1);
  }
  fprintf(f, "Some text: %s\n",line);
  fclose(f);
}

用空格替換制表符

char* replacet (char *text, int tabsize, int tabanz){
    int newsize=strlen(text)+tabsize*tabanz-tabanz;
    char newtext[newsize];//Wenn \t nu ein zeichen ist
    char* ptrnew=newtext;
    char* ptr=text;
    for(int i=0;i<strlen(text);i++,ptr++){
        if(text[i]=='\t'){
            for(int j=0;j<tabsize;j++){
                *ptrnew=' ';
                ptrnew++;
            }
        }else{
            *ptrnew=text[i];
            ptrnew++;
        }
    }
    char* newtextptr=newtext;
    return newtextptr;
}

讀取在命令行界面上輸入的行

char* readcli(){
    char *buffer;
    size_t bufsize = 64;
    size_t chars;
    buffer = (char *)malloc(bufsize * sizeof(char));
    if( buffer == NULL){
        perror("Error malloc");
    }    
    printf("Type something with Tabulators: ");
    chars = getline(&buffer,&bufsize,stdin);
    printf("%zu characters were read.\n",chars);
    return buffer;
}

請幫助我,我不知道該如何解決。 謝謝

兩個問題:

  • 這里

     char* replacet (char *text, int tabsize, int tabanz){ int newsize=strlen(text)+tabsize*tabanz-tabanz; char newtext[newsize];//Wenn \\t nu ein zeichen ist ... char* newtextptr=newtext; return newtextptr; /* <-- HERE */ 

    返回局部變量( newtext )的地址。 內存僅在函數內部有效。

    函數返回內存的那一刻會自動釋放。 返回函數后訪問它會調用臭名昭著的Undefined Behaviour。 此刻什么都可能發生。 不要這樣做。

  • 函數replacet()丟失0終止新的C-“ string”。

要解決所有這些替換

  char newtext[newsize];

通過

  char * newtext = malloc(newsize + 1); /* +1 for 0-terminator each
                                           c-"string" needs */
  if (NULL == newtext) /* Error checking is debugging for free. */
  {
    return NULL;
  }

離開前添加0終止符:

  newtext[i] = '\0'; /* or just the equivalent: ... = 0; */
  char* newtextptr = newtext;
  return newtextptr;
}

從更改呼叫代碼

  line=replacet(line,t,countt(line));

  {
    char * pctmp = replacet(line, t, countt(line));
    if (NULL == pctmp)
    {
      /* exit or do what error handling made sense */
      exit(EXIT_FAILURE); /* include stlib.h for the EXIT_* macros */
    }
    else
    {
      free(line);
      line = pctmp;
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM