提问人:sgrandom 提问时间:11/26/2022 更新时间:11/26/2022 访问量:21
更改数组的值,但最终导致最后两个值重复
Changing values of an array but ending up with the last two values being duplicates
问:
我正在编写的程序的一部分将数组中的某个值替换为数组中的下一个值。但是,它最终导致数组中的最后两个值相同。有没有办法将最后一个值替换为 NULL?
这是当前输出
found it again
Array value 0: cat:
Array value 1: file1.txt:
Array value 2: output.txt:
Array value 3: output.txt:
Array value 4: (null):
Array value 5: (null):
This is the first line in file1.txt
This is the last line
这是我尝试替换最后一个值时的输出将 null,但它返回分段错误
found it again
Array value 0: cat:
Array value 1: file1.txt:
Array value 2: output.txt:
Array value 3: (null):
Array value 4: (null):
Array value 5: (null):
这是完整的代码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#define BUFFERSIZE 1024
int main(int argc, char* argv[])
{
int fd_out = dup(STDOUT_FILENO);
int fd_in = dup(STDIN_FILENO);
argc++;
char buf[BUFFERSIZE];
int n;
printf("Please enter commands: \n");
while ((n = read(STDIN_FILENO, buf, BUFFERSIZE)) > 0)
{
buf[n] = 0;
buf[strlen(buf)-1] = '\0';
int i = 0;
char* array[10];
char* token1 = strtok(buf, " ");
while ((token1 != NULL))
{
array[i++] = token1;
token1 = strtok(NULL, " ");
}//while
array[i] = NULL;
if (strcmp(buf, "exit") == 0)
{
break;
}//if
for (int j = 0; j < i; j++)
{
if (!strcmp(array[j], ">"))
{
char* filename_out = array[j+1];
printf("STDOUT redirected\n");
printf("found it\n");
int file_out = open(filename_out, O_WRONLY | O_CREAT, 0777);
int file2_out = dup2(file_out, 1);
for(int k = j; k < i-1; k++)
{
array[k] = array[k + 1];
}//if
array[i] = NULL;
printf("found it again\n");
if ((file_out | file2_out) == -1)
{
return 1;
}//if
//array[i-1] = NULL;
for (int j = 0; j < i+2; j++)
{
printf("Array value %d: %s:\n", j, array[j]);
}//for*/
}//if
if (!strcmp(array[j], "<"))
{
char* filename_in = array[j+1];
printf("STDIN_FILENO redirected\n");
int file_in = open(filename_in, O_WRONLY | O_CREAT, 0777);
int file2_in = dup2(file_in, 0);
for(int l = j; l < i - 1; l++)
{
array[l] = array[l + 1];
}//for
if ((file_in | file2_in) == -1)
{
return 1;
}//if
}
}//for
for (int i = 1; i < argc; i++)
{
pid_t pid;
if (argc >= 1)
{
if ((pid = fork()) < 0)
{
perror("fork");
}//if
else if (pid == 0)
{ // child process
if (execvp(array[0], array) == -1)
{
perror("execvp");
return EXIT_FAILURE;
} // if
}//else if
else
{ // parent process
int status;
wait(&status);
//int again_out = dup2(fd_out, 1);
//int again_in = dup2(fd_in, 0);
if ((again_out | again_in) == -1)
{
return 1;
}
printf("Please enter commands again: \n");
}//else
}//if
else
{
fprintf(stderr, "Please specify the name of the program to exec as a command line argument\n");
return EXIT_FAILURE;
}//if
}//for
}//while
if (n == -1) perror("read");
}//main
我尝试使用(其中是数组的大小),但它返回分段错误array[i-1] = NULL;
i
答: 暂无答案
评论
buf
fork()
execvp()