RPC C程序中的fprintf问题

时间:2012-04-29 00:44:26

标签: c rpc

我在RPC程序中遇到fprintf问题。它会打开一个文件,但不会将内容读入文件。它将使用printf打印内容,但fprint将文件留空。我该如何解决这个问题?谢谢

#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 个答案:

答案 0 :(得分:3)

在您的int writefile (char *content);函数中,您当前正在使用close(fp1);。相反,要关闭文件,您应该fclose(fp1)代替。