在 C 文件中查找和替换

发布于 2024-09-14 05:37:01 字数 1382 浏览 3 评论 0原文

问题是查找并替换 C 文件中的字符串

我是 C 文件新手。我尝试了以下代码,但没有得到任何输出:

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        FILE *f1,*f2;
        char *src,*dest,*s1,ch,ch1,ch2,ch3;
        int i;
        f1=fopen("input.txt","rw");
        f2=fopen("dummy.txt","rw");
        src="mor";
        dest="even";
        while(ch!=EOF)
        {
         ch=fgetc(f1);
         if(ch==src[0])                      //Finding 1st char of src
         {
         fgets(s1,strlen(src),f1);
         if(strcmp(src+1,s1)==0)         //Finding occurance of "src" in file
         {
          fseek(f1,strlen(src)-1,SEEK_CUR);
          while(ch1!=EOF)             //Copying remaining data into another file
          {
          ch1=fgetc(f1);
          fputc(ch1,f2);
          }
      fseek(f1,-strlen(src),SEEK_CUR);
      for(i=0;i<strlen(dest);i++)  //replacing "src" with "dest"
      {
          ch2=dest[i];
          fputc(ch2,f1);
      }
      fclose(f1);
      f1=fopen("input.txt","a");
      while(ch3!=EOF)      //Appending previosly copied data into 1st file
      {
          ch3=fgetc(f2);
          fputc(ch3,f1);
      }
     }
   }
 }
     fclose(f1);
     fclose(f2);
}

The Contents of input.txt is "morning".

请指出逻辑中的错误,并给出一个有效的代码相同。

提前致谢。

The Problem was to find and replace a string in a C File.

I am new to C Files. I have tried the following code but I didnt get any output:

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        FILE *f1,*f2;
        char *src,*dest,*s1,ch,ch1,ch2,ch3;
        int i;
        f1=fopen("input.txt","rw");
        f2=fopen("dummy.txt","rw");
        src="mor";
        dest="even";
        while(ch!=EOF)
        {
         ch=fgetc(f1);
         if(ch==src[0])                      //Finding 1st char of src
         {
         fgets(s1,strlen(src),f1);
         if(strcmp(src+1,s1)==0)         //Finding occurance of "src" in file
         {
          fseek(f1,strlen(src)-1,SEEK_CUR);
          while(ch1!=EOF)             //Copying remaining data into another file
          {
          ch1=fgetc(f1);
          fputc(ch1,f2);
          }
      fseek(f1,-strlen(src),SEEK_CUR);
      for(i=0;i<strlen(dest);i++)  //replacing "src" with "dest"
      {
          ch2=dest[i];
          fputc(ch2,f1);
      }
      fclose(f1);
      f1=fopen("input.txt","a");
      while(ch3!=EOF)      //Appending previosly copied data into 1st file
      {
          ch3=fgetc(f2);
          fputc(ch3,f1);
      }
     }
   }
 }
     fclose(f1);
     fclose(f2);
}

The Contents of input.txt is "morning".

Kindly point the ERROR in the logic and also give an efficient code for the same.

Thanks in Advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

俏︾媚 2024-09-21 05:37:01

用 C 语言读取文件通常有点混乱。我看到的第一个问题是主循环中使用 ch 的方式。第一次执行时

while (ch != EOF)

,ch未初始化,如果恰好持有EOF,则主循环根本不会执行。我通常使用以下结构来读取文件:

FILE *fInput = fopen("input.txt", "r");
int ch; /* need an int to hold EOF */

for (;;)
{
    ch = fgetc(fInput);
    if (ch == EOF) break;

    ...
}

此外,您可能需要阅读文件指针概念。例如,在读取 src 的剩余部分后,您可以使用 fseek() 前进,并在将数据复制到 f2 之前跳过更多字符。本质上,您读取m,读取or(使用fgets()) - 并进入未分配的缓冲区s1,这将在不久的将来的某个时间对你进行 ka-boom),再跳过 2 个字符(现在你的指针位于“morning”的最后 n 个),将“ng”复制到 f2 中,尝试写入 EOF在此循环中到 f2 (因此上面的读取模式直到 EOF),向后查找两个字符(一旦到达 EOF 可能会失败,我的 C 文件函数有点这些天生锈了),向 f1 写入“even”(如果我对 EOF 后的查找错误,则应该将输入文件设置为“mornieven”,如果我是正确的,则不要更改它)。总之,我认为代码没有达到您的预期目的。

我建议建立你的功能。以下每一项都可以编写为一个程序,您应该在进入下一步之前测试并完成该程序:

  1. 安全地读取文件,并将其打印出来
  2. 检测src的内容,并打印其余部分输入
  3. 将其余输入保存到第二个文件,而不是打印
  4. 在第一个文件中将 src 替换为 dest ,并忽略其余部分(因为您使用“rw”打开输入文件,这将截断其余的输入)。您可能需要执行 fseek() 来清除 EOF 状态。另请查看 ftell() 记录一个位置,您可以使用 fseek() 跳转回该位置。
  5. 最后,在替换 后将保存的所有内容复制到第二个文件中srcdest (这里不需要关闭 f1。但最好以写入方式打开 f2,从第一个文件复制后关闭,然后以读取方式重新打开以执行复制回 f1 的操作)。

此外,当您需要缓冲区(例如 s1)时,暂时使用足够大的数组即​​可,但请查看 malloc()free() 函数来执行针对此类情况的动态内存分配。

Reading files in C is usually a bit messy. The first problem that I see is the way ch is used in the main loop. The first time

while (ch != EOF)

is executed, ch is uninitialized, and if it happens to hold EOF, the main loop will not execute at all. I usually use the following structure for reading from files:

FILE *fInput = fopen("input.txt", "r");
int ch; /* need an int to hold EOF */

for (;;)
{
    ch = fgetc(fInput);
    if (ch == EOF) break;

    ...
}

In addition, you may need to read up on file pointer concept. For example, after reading the remainder of src, you fseek() forward, and skip some more characters before you copy data to f2. Essentially, you read m, read or (with fgets() - and into an unallocated buffer s1 that would go ka-boom on you some time in the near future), skip 2 more characters (now your pointer is at last n of "morning"), copy "ng" into f2, try to write EOF to f2 in this loop (hence the above pattern for reading until EOF), seek two characters back (which may fail once you reach EOF, my C file functions are a bit rusty these days), write "even" to f1 (which should, if I am wrong about seek after EOF, set input file to "mornieven", and not change it if I am correct). In summary, I don't think the code does what you intend it to do.

I would recommend building up your function. Each one of the following can be written as a program that you should test and finish before going to next step:

  1. read the file safely, and print it out
  2. detect the contents of src, and print the rest of input
  3. save the rest of the input to second file instead of printing
  4. replace src with dest in first file, and ignore the rest (since you open input file with 'rw', this will truncate the rest of input). You may need to do an fseek() to clear the EOF status. Also look at ftell() to record a position that you can jump back to using fseek()
  5. finally, copy in everything you have saved to second file after replacing src with dest (no need to close f1 here. But it is better to open f2 as write, close after copy from first file, and reopen as read to perform the copy back to f1).

In addition, when you need a buffer (such as s1), just use a large enough array for now, but look into malloc() and free() functions to perform dynamic memory allocations for situations like these.

初见 2024-09-21 05:37:01

进行替换的一种简单方法是首先将整个文件读入缓冲区,

例如

FILE* fpIn = fopen("file.txt","rb");
fseek(fpIn, 0L, SEEK_END);
size_t s = ftell(fpIn);
fseek(fpIn, 0L, SEEK_SET);
void* buf = malloc(s);
fread(buf,s,1,fpIn);

现在,在编写文件时,检查您的字符串

char src[] = "mor";
char dest[] = "even";
int lenSrc = strlen(src);
int lenDest = strlen(dest);
for (char* ch = buf; ch < buf + s; ++ch)
{
   if ( !memcmp( ch, src, lenSrc ) )
   {
     fwrite( dest, 1,lenDest, fpOut );
     ch += lenSrc;
   }
   else 
   {
     fputc( *ch, fp );
   }
}

免责声明:尚未编译此文件

One simple way to do the replace would be to first read in the whole file into a buffer

e.g.

FILE* fpIn = fopen("file.txt","rb");
fseek(fpIn, 0L, SEEK_END);
size_t s = ftell(fpIn);
fseek(fpIn, 0L, SEEK_SET);
void* buf = malloc(s);
fread(buf,s,1,fpIn);

now while writing the file, check for your string

char src[] = "mor";
char dest[] = "even";
int lenSrc = strlen(src);
int lenDest = strlen(dest);
for (char* ch = buf; ch < buf + s; ++ch)
{
   if ( !memcmp( ch, src, lenSrc ) )
   {
     fwrite( dest, 1,lenDest, fpOut );
     ch += lenSrc;
   }
   else 
   {
     fputc( *ch, fp );
   }
}

disclaimer: haven't compiled this

倾城°AllureLove 2024-09-21 05:37:01

您在输出中打印了错误的内容。打印“ch”,而不是文件指针。

 while(ch!=EOF) 
 { 
     ch=getc(f1); 
     printf("%c",ch); 
 } 
 while(ch!=EOF) 
 { 
     ch=getc(f2); 
     printf("%c",ch); 
 }

此外,f2 在输出期间最后关闭。您必须重新打开它(就像使用 f1 一样。)

You are printing the wrong thing in your output. Print, "ch", not the file pointer.

 while(ch!=EOF) 
 { 
     ch=getc(f1); 
     printf("%c",ch); 
 } 
 while(ch!=EOF) 
 { 
     ch=getc(f2); 
     printf("%c",ch); 
 }

Also, f2 is closed at the end during your output. You'll have to reopen it (just like you do with f1.)

我的痛♀有谁懂 2024-09-21 05:37:01

乍一看,我发现您调用 fgets 的代码是错误的。您尚未分配任何内存,并且正在将字符串读入未初始化的指针中。读入数组或动态分配的内存。

At first glance, I see that your code to call fgets is wrong. You have not allocated any memory and you are reading a string into an uninitialized pointer. Read into an array or dynamically allocated memory.

很快妥协 2024-09-21 05:37:01

另一个问题是您将 ch 声明为 charfgetc() 返回一个 int,这是有充分理由的。能够返回任何可能的字符或 EOF 是件好事,因此 EOF 不应该是字符,因此理想情况下 fgetc() 返回比 char 更大的类型。

结果是循环很可能永远不会结束,因为在某些标准实现上 ch 不可能保存 EOF。将其(以及 ch1ch3)声明为 int

Another problem is that you are declaring ch as char. fgetc() returns an int, and for good reason. It is good to be able to return any possible character or EOF, so EOF shouldn't be a character, so ideally fgetc() returns a bigger type than char.

The upshot is that the loop may well never end, since ch can't possibly hold EOF on some standard implementation. Declare it (and ch1 and ch3) as int.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文