gpt4 book ai didi

c - 不打印文件的前 5 个字符

转载 作者:行者123 更新时间:2023-11-30 20:26:45 26 4
gpt4 key购买 nike

从文件读取并打印结果的循环不会打印所有读取文件的前 5 个字符。如果我一次打印 1 个字符,效果很好,但我正在从文件中读取 float ,需要稍后处理。这些数字由空格分隔,这就是为什么我只在遇到空格时才尝试打印。

这是我的源代码

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

#define BUFFER_SIZE 100
#define READ_END 0
#define WRITE_END 1

//main function
int main(int argc, char *argv[])
{
//process ids
int processIds[argc - 1];
int pipes[argc - 1][2];
char *fileNames[argc - 1];
int status;

//check if at least one data file
if (argc == 1)
{
return -1;
//end program
}

//get file names and store in array fileNames
int i;
for (i = 0; i < (argc - 1); i++)
{
fileNames[i] = argv[i + 1];
}

//create child processes
for (i = 0; i < (argc - 1); i++)
{
//make a pipe for communication
if (pipe(pipes[i]))
{
printf("bad pipe");
return -1;
}
//make a child process
processIds[i] = fork();

//check if child or paren process
if (processIds[i] == 0)
{
//child process
//close unused end

close(pipes[i][READ_END]);

//make file
FILE *dataset = fopen(fileNames[i], "r");

//test if file opened
if (dataset == 0)
{
printf("could not find/open file");
return -1;
}

//read and process file
char *x;
char *num = "";
int min, max;
while ((*x = fgetc(dataset)) != EOF)
{
if ((x == " ") || (x == "\t") || (x == "\n"))
{
//end of number
printf("A%s B%s", num, num);
num = "";
}
else
{
strcat(num, x);
}
//printf("%c", x);
}
printf("\n\n");
char msg[BUFFER_SIZE];

write(pipes[i][WRITE_END], msg, strlen(msg) + 1);
fclose(dataset);
exit(0);
}
else if (processIds[i] < 0)
{
//error
return -1;
}
else
{
//parent process closes write end of pipe
close(pipes[i][WRITE_END]);
}
}

//wait for children
for (i = 0; i < (argc - 1); i++)
{
//create a read buffer
char read_buf[BUFFER_SIZE];

//wait and get pid of completed child
int pid = wait(&status);

//find which child completed
int j = 0;
while (pid != processIds[j] && j < (argc - 1))
{
//pid not recognized, should not happen
if (j >= (argc - 1))
{
printf("bad pid");
return -1;
}
j++;
}
//read from completed child
read(pipes[j][READ_END], read_buf, BUFFER_SIZE);
}

return 0;
}

最佳答案

我可以发现您的代码存在以下错误:

1) 内存分配

您需要分配您的num变量

示例:

char *num = malloc(10);

2) 返回类型

'fgetc' 不返回指针或字符,因此您应该定义

int x;

x = fgetc(dataset);

3) 你的条件是错误的

if ((x == ' ') || (x == '\t') || (x == '\n'))

请注意,' ' 不是 ""

<小时/>

现在作为我阅读这些单独字符串的建议:

1)读取缓冲区中的所有文件:

char buff[SIZE];
dataset= fopen("fileName.txt", "r");
if( dataset!= NULL ){
while ( !feof(fp ) ){
memset(buff, '\0', sizeof( buff) );
fgets(buff, SIZE, (FILE*)dataset);
}
fclose(dataset);
}

2) 使用 strchr 查找下一个空格并打印字符串 see example of use here

关于c - 不打印文件的前 5 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24254406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com