【问题标题】:About using low-level functions关于使用低级函数
【发布时间】:2017-11-04 13:14:03
【问题描述】:

我接受了评论并重写了代码。但它仍然不起作用。 我打开一个包含多个句子的文本文件,将小写字母更改为大写字母,然后尝试在另一个文件中输入它们。 我不太清楚 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);
}

【问题讨论】:

  • 你为什么要写sizeof(txt),知道你可能少写read()
  • 阅读手册。 open 以负值失败。 0 是一个有效的文件描述符。 read 可能会以小于sizeof(txt) 的值成功返回,并且它肯定不会在读取字符串后放置'\0 -- 使用返回的数字(如果是正数)作为读取字符串的长度。
  • @EOF 说什么,加上 'strlen(txt)' 为什么? read() 返回一个值 - 你应该使用它。所有那些 sizeof、strlen 之类的都是错误的;不必要的、不安全的、不需要的。
  • 您认为可以同时读写同一个文件的信念比大多数人都更聪明。
  • 关于:int fp; 调用 open() 的返回值是文件描述符索引,而不是文件指针,建议:fd_inint ftp; 存在类似的考虑@ 变量名称应表明contentusage(或更好,两者兼有),发布代码中使用的变量名称具有误导性

标签: c linux


【解决方案1】:

以下建议代码:

  1. 将 cmets 合并到问题中
  2. 记录包含每个头文件的原因
  3. 通过使用toupper() 稍微澄清了代码
  4. 正确检查错误
  5. 自行清理
  6. 使用有意义的变量名
  7. 通过赋予有意义的名称来消除“神奇”数字
  8. 遵循公理:每行只有一个语句,并且(最多)每个语句有一个变量声明。
  9. 干净编译
  10. 执行所需的功能,从输入文件读取一个块(最多 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多