首页 > 解决方案 > 使用管道文件传输名称

问题描述

我有 3 个名为 pre、sort 和 pipe 的“.c”文件。Pre 从控制台获取用户输入的姓名和 GPA。如果 GPA 大于或等于 3.0,则将名称存储到结构中。

这是 pre.c 文件:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct student{
  char temp_name[50];
  char names[50];
};

int main()
{
  int read_index = 0;
  float check_gpa;

  struct student data[read_index];

  printf("Enter student name and GPA: \n");
  scanf("%s %f\n", data[read_index].temp_name, &check_gpa);
  read_index++;

  while(scanf("%s %f\n", data[read_index].temp_name, &check_gpa) != EOF)
       {
         if (check_gpa >= 3.0)
            {
              strcpy(data[read_index].names, data[read_index].temp_name);
              read_index++;
            }
       }

  return 0;
}

管道文件链接 pre 和 sort 文件,以便将 pre 中的数据发送到 sort。

这是 pipe.c 文件:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>

int main()
{
  char *args[] = {"./sort", NULL};
  char *argv[] = {"./pre", NULL};

  int pipe_end[2];
  int pipe_id;
  pipe(pipe_end);

  if (pipe(pipe_end)==-1) // Check for pipe functionality
    {
        perror("Pipe Failed");
        return 1;
    }

  pipe_id = fork();

  if (pipe_id < 0) //Check for fork functionality
  {
    printf("Fork failed");
    return 1;
  }
  else if(pipe_id == 0)//Child
  {
    close(pipe_end[0]);
    dup(pipe_end[0]);
    execvp(argv[0], argv);
  }
  else //Parent
  {
    wait(NULL);
    close(pipe_end[1]);
    dup2(pipe_end[1], 0);
    close(pipe_end[0]);
    execvp(args[0], args);

  }

  return 0;
}

排序文件从结构数组中获取名称并按字母顺序对它们进行排序并将它们打印到控制台。这就是问题开始的地方,因为当我运行管道文件时,我可以输入名称和 GPA 但是当我通过按 Ctrl+D 启动 EOF(这是必需的并且无法更改)时,我期待字符串被发送到排序并按字母顺序显示,但这不会发生。

这是 sort.c 文件:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>

struct student{
  char temp_name[50];
  char names[50];
};

int main()
{
  int print_index1 = 0,
      print_index2,
      read_index,
      SIZE;

struct student data[print_index1];

SIZE = print_index1;


printf("Students with GPA's greater than or equal to 3.0, listed in alphabetical order:\n ");
for(print_index1 = 0; print_index1 < SIZE; print_index1++)
   {

            for(print_index2 = print_index1 + 1; print_index2 < SIZE; print_index2++)
               {
                  if(strcmp(data[print_index1].names, data[print_index2].names) > 0)
                    {
                      strcpy(data[print_index1].temp_name, data[print_index2].names);
                      strcpy(data[print_index2].names, data[print_index1].names);
                      strcpy(data[print_index1].names, data[print_index1].temp_name);

                    }
                }

      printf("%s\n", data[print_index1].names);
    }

  return 0;
}

我已经使用用户输入独立测试了这两个文件并且它们工作。但是出现了一个新问题,如果您查看排序文件并注意到我有一个 while 循环,它需要一个我认为有意义的 for 循环条件>它在一周前工作但现在它没有(除非它是吸虫)。但这是我的困境,我似乎无法将用户输入从“pre.c”转移到“sort.c”,我非常感谢一些帮助。我还认为“sort.c”文件中的 while 循环导致打印名称出现问题。

标签: c

解决方案


推荐阅读