Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从file.txt read by read系统调用中获取字符串的子字符串_C_Linux_System Calls - Fatal编程技术网

C 从file.txt read by read系统调用中获取字符串的子字符串

C 从file.txt read by read系统调用中获取字符串的子字符串,c,linux,system-calls,C,Linux,System Calls,假设我们有一个包含以下内容的文件lista.txt: John abc Mark cdf Susie hhh 我怎样才能得到每行的第一个单词?(John和Mark和Susie) 这是我的代码: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait

假设我们有一个包含以下内容的文件
lista.txt

John abc
Mark cdf
Susie hhh
我怎样才能得到每行的第一个单词?(
John
Mark
Susie

这是我的代码:

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

#define BUF_DIM 1000

struct elem{
    char nome[BUF_DIM];
};


int main() 
{
    int fileDescriptor;
    int nread;
    char carattere;
    char nickname[BUF_DIM];
    int i = 0, times = 0;

    struct elem *top = NULL;

    // Apertura del file in sola lettura
    if( (fileDescriptor=open("lista.txt", O_RDONLY)) == -1 ){
        perror("Errore con apertura del file");
        exit(1);
    }

    // Lettura del file
    while( read(fileDescriptor, &carattere, 1) == 1){ // un byte alla volta
        if (carattere != ' ') {
            times++;
            //printf("%c\n", carattere);
            nickname[i++] = carattere;
            //printf("%c\n", nickname[i++])
        }
        else {
            nickname[i++] = ' ';
        }
    }

    nickname[times] = '\0';

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


    close(fileDescriptor);

    return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#定义BUF_尺寸1000
结构元素{
字符名称[BUF_DIM];
};
int main()
{
int文件描述符;
国际nread;
焦克拉特;
字符昵称[BUF_DIM];
int i=0,时间=0;
struct elem*top=NULL;
//sola lettura中的Apertura del文件
如果((fileDescriptor=open(“lista.txt”,orduonly))=-1){
perror(“文件错误”);
出口(1);
}
//Lettura del文件
while(read(fileDescriptor,&caratter,1)==1){//un byte alla volta
如果(克拉特!=''){
时代++;
//printf(“%c\n”,克拉特);
昵称[i++]=克拉特;
//printf(“%c\n”,昵称[i++])
}
否则{
昵称[i++]='';
}
}
昵称[次数]='\0';
printf(“%s\n”,昵称);
关闭(文件描述符);
返回0;
}

使用
read
读取文本文件非常麻烦。使用标准流函数,
fopen()
/
fclose()
fgets()
甚至
fscanf()
,会简单得多

如果必须使用
read
系统调用,我建议您实现一个函数,使用
read
复制循环中的行内容,从文本文件中读取一行,每次读取一个字节


请注意,
perror(“lettura中的错误”)”是不合适的。

为了找到每行中的第一个字,您首先需要拆分为多行。 每行末尾都有一个特殊字符。您可以通过比较
\n
找到它

如果需要解析所有单词,请分配一个缓冲区,该缓冲区可容纳2行并一直读取,直到找到
\n
。然后解析缓冲区中的行并删除它

如果您只需要第一个单词,我建议您先阅读,直到找到空白,然后跳过,直到
\n