gpt4 book ai didi

c - 关于使用低级函数

转载 作者:行者123 更新时间:2023-11-30 21:27:55 25 4
gpt4 key购买 nike

我采纳了评论并重写了代码。但它仍然不起作用。我打开一个包含几个句子的文本文件,将小写字母更改为大写字母,然后尝试将它们输入到另一个文件中。我不太清楚 read() 的第三个参数使用什么。如何更正代码?

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
int fp,ftp,i,nread;
char str[300];


if(fp=open("text_in",O_RDONLY) < 0)
{
perror("open: ");
exit(1);
}

if(ftp=open("text_w", O_WRONLY |O_CREAT , 0644) < 0)
{
perror("open: ");
exit(1);
}


nread=read(fp,str,300);

for(i=0; i<=nread; i++)
{
if((str[i] >= 'a') && (str[i] <= 'z'))
{
str[i] -= ('a'-'A');
}
}

write(ftp,str,nread);


close(fp);
}

最佳答案

以下建议代码:

  1. 合并对问题的评论
  2. 记录了包含每个头文件的原因
  3. 通过使用 toupper() 稍微澄清了代码
  4. 正确检查错误
  5. 自行清理
  6. 使用有意义的变量名称
  7. 通过赋予有意义的名称来消除“神奇”数字
  8. 遵循公理:每行只有一个语句,并且每个语句(最多)一个变量声明。
  9. 干净地编译
  10. 执行所需的功能,从输入文件中读取一个 block (长度最多 300 个字符),将所有小写字符转换为大写,并将更新后的行输出到新文件。

现在,建议的代码:

#include <stdio.h>    // perror()
#include <stdlib.h> // exit()
#include <fcntl.h> // open(), O_RDONLY, O_WRONLY, O_CREAT
#include <unistd.h> // read(), write(), close()
#include <ctype.h> // toupper()

#define BUF_LENGTH 300

int main( void )
{
int fdi;
int fdo;
char buffer[ BUF_LENGTH ];


if( (fdi=open("text_in",O_RDONLY)) < 0)
{
perror("open: ");
exit(1);
}

if( (fdo=open("text_w", O_WRONLY |O_CREAT , 0644)) < 0)
{
perror("open: ");
close( fdi ); // cleanup
exit(1);
}


ssize_t nread = read( fdi, buffer, BUF_LENGTH );
if( nread <= 0 )
{ // then EOF or read error
perror( "read failed" );
close( fdi );
close( fdo );
exit( 1 );
}

for( ssize_t i=0; i<=nread; i++ )
{
buffer[i] = (char)toupper( buffer[i] );
}

ssize_t nwritten = write( fdo, buffer, (size_t)nread );
if( nwritten != nread )
{
perror( "write all, bytes failed" );
}

close(fdi);
close(fdo);
}

关于c - 关于使用低级函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47111135/

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