【问题标题】:c program function not working properlyc程序功能无法正常工作
【发布时间】:2018-08-20 09:07:03
【问题描述】:
#include<stdio.h>
#include<string.h>

void createIndexFile(char[]);

int main()
{
    FILE *fp;
    char fname[40];
    int option;

    printf("\nEnter the filename to open: ");
    scanf("%s",fname);

    fp=fopen(fname,"r");
    if(fp==NULL)
    {
        printf("\nCannot open the file\n");
        return 0;
    }
    else
    {
        printf("\n%s",fname);
        createIndexFile(fname);
    }

    while(1)
    {
        printf("\n*****MENU*****\n");
        printf("\n1.Display ......\n2.Insert new data\n3.Find data\n4.Display data\n5.Exit\n");
        printf("\nChoose an operation: ");
        scanf("%d",&option);

        switch(option)
        {
            case 1: break;

            case 2: break;

            case 3: break;

            case 4: break;

            case 5: return 0;

            default: printf("\nInvalid selection\n");
         }
    }
}

void createIndexFile(char fname[])
{
    int i=0;
    char tempFile[40];
    char indexFile[40];

    printf("\n%s",fname);

    strcpy(indexFile,"xyz");
    strcpy(tempFile,fname);

    while(tempFile[i]!='.')
    {
        if(tempFile[i]=='/')
        tempFile[i]='_';
    }
    strcat(tempFile,".idx");
    strcat(indexFile,tempFile);
    printf("\nIndex File Name: %s",indexFile);
}

这是一个程序,在输入文件名后假设/home/abc.txt,我的名字是xyz,那么应该创建一个索引文件xyz_home_abc.idx

输入文件名后,如果存在,应该转到else部分和函数

createIndexFile(fname);

应该被调用。但是在函数内部,没有任何东西可以正常工作。如果我们打印一个字符或其他东西,它就会被打印出来。但是,如果我尝试给另一个 printf 它不起作用。

【问题讨论】:

  • 你在while(tempFile[i]!='.') 循环中错过了i++;
  • 好了,是时候学习如何使用调试器了。
  • 非常感谢。我忘了在 while 循环中增加 'i'。

标签: c function file


【解决方案1】:

更正了你的功能

void createIndexFile(char fname[])
{
    int i=0;
    char tempFile[40];
    char indexFile[40];
    printf("\n%s",fname);
    strcpy(indexFile,"");
    while(fname[i]!='.')
    {
        if(fname[i]=='/')
         tempFile[i]='_';
        else
         tempFile[i]=fname[i];
      i++;
    }
     tempFile[i]='\0';
    strcat(tempFile,".idx");
    strcat(indexFile,tempFile);
    printf("\nIndex File Name: %s",indexFile);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2013-10-29
    • 1970-01-01
    相关资源
    最近更新 更多