2012-04-29 42 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