2012-04-29 86 views
3

我在我的RPC程序中遇到了fprintf問題。它打開一個文件,但不會將內容讀入文件。它將使用printf打印內容,但是fprint將文件留空。我該如何解決這個問題?謝謝在RPC C程序中的fprintf問題

#include <rpc/rpc.h> 
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include"lab5.h" 

char * filename(char *str) 
{ 

    file = str; 
    printf("filename = %s\n",file); 
    return file; 
} 

int writefile(char *content) 
{ 
    FILE *fp1; 
    fp1 = fopen("recfile.txt", "w"); 
    if(fp1 == NULL) 
    { 
     printf("File can't be created\n"); 
     return 0; 
    } 
    printf("%s\n",content); 
    int i = fprintf(fp1, "%s", content); 
    printf("i = %d\n",i); 
    close(fp1); 
    return 1; 
} 

int findwordcount(char* searchword) 
{ 
    char *grep; 
    int count; 
    int status; 
    FILE *fp; 
    grep = (char*)calloc(150, sizeof(char)); 
    strcpy(grep, "grep -c \""); 
    strcat(grep, searchword); 
    strcat(grep, "\" "); 
    strcat(grep, "recfile.txt"); 
    strcat(grep, " > wordcount.txt"); 
    status = system(grep); 
    printf("status = %d\n", status); 
    if(status != 0) 
    { 
     count = 0; 
    } 
    else 
    { 
     fp = fopen("wordcount.txt", "r"); 
     fscanf(fp, "%d", &count); 
     printf("count = %d\n", count); 
    } 
    return count; 
} 
+1

什麼是返回值?這也不是問題,但是您不會在'findwordcount()'中關閉''wordcount.txt'''。 – twain249 2012-04-29 00:47:07

+0

'writefile()'沒有問題。無論您的內容是空的還是您在其他地方修改了'recfile.txt'。 – 2012-04-29 00:55:13

+0

@KingsIndian他說'printf'正在工作,所以我會猜測後面的。 – twain249 2012-04-29 00:56:12

回答

3

在你的函數int writefile (char *content);您當前使用close(fp1);。取而代之的是關閉文件,您應該改爲fclose(fp1)

+1

+1:斑點。這也意味着應該有編譯錯誤或警告(至少''close()'沒有被聲明)。如果沒有,那麼OP需要打開更多的編譯警告,或者獲得更好的編譯器。 – 2012-04-29 03:59:32

+0

謝謝你是這個問題。 – 2012-04-29 16:30:07