3

我在我的 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;
}
4

1 回答 1

3

在您int writefile (char *content);当前使用的函数中close(fp1);。而不是关闭文件,你应该fclose(fp1)改为。

于 2012-04-29T03:42:28.030 回答