【问题标题】:fprintf issues in RPC C programRPC C 程序中的 fprintf 问题
【发布时间】:2012-05-09 06:34:02
【问题描述】:

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

【问题讨论】:

  • 返回值是多少?这也不是问题,但您没有在findwordcount() 中关闭"wordcount.txt"
  • writefile() 没有问题。您的content 为空,或者您在其他地方修改recfile.txt
  • @KingsIndian 他说printf 正在工作,所以我猜是后者。

标签: c rpc


【解决方案1】:

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

【讨论】:

  • +1:很好看。这也意味着应该有编译错误或警告(至少没有声明close())。如果没有,那么 OP 需要打开更多的编译警告,或者获得更好的编译器。
  • 谢谢你的问题。
猜你喜欢
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
相关资源
最近更新 更多