c - 如何在 Linux 中使用 C 语言使用“写入”系统调用?
问题描述
我的代码工作正常。我得到的唯一错误是在程序将文本写入文件即 text1.txt 后,当我实际打开它时,文本文件会打印一些奇怪的符号,如 /00。
int fd;
fd = open("text1.txt", O_RDWR);
char text[] = "This is my file.";
write(fd,text,sizeof(text));
解决方案
- 您需要确保
open
成功而不是盲目地写入文件描述符。- 始终检查系统调用(和大多数 C 标准库函数)
errno
的返回值,并检查返回值是否指示错误。
- 始终检查系统调用(和大多数 C 标准库函数)
- 您的字符串文字将在点后包含一个隐藏的
\0
(NULL
)字符。- 因此,直接写入
text
文件将包括\0
您所看到的尾随。
- 因此,直接写入
这些问题可以通过以下方式纠正:
始终检查系统调用的返回值 - 在这种情况下:将有用的错误消息打印到标准输出并执行任何必要的清理(
goto closeFile;
语句)。- 因为 C 没有本机
try/catch
或 RAII,这意味着很难编写简洁的错误处理和清理代码,但在 C 中通常可以接受goto
用于常见的清理代码,因此声明。goto closeFile
- 因为 C 没有本机
用于
strlen
获取字符串的实际长度。- 尽管在紧要关头,
sizeof(text) - 1
只要您处于 C 编译器知道的长度的范围内,如果由于数组指针衰减而text
越过函数边界,使用sizeof()
将不起作用。
- 尽管在紧要关头,
像这样:
void writeToFile() {
int fd = open( "text1.txt", O_CREAT | O_WRONLY ); // Use `O_WRONLY` instead of `O_RDWR` if you're only writing to the file. Use `O_CREAT` to create a file if it doesn't already exist.
if( fd == -1 ) {
printf( "Error opening file: errno: %d - %s\n", errno, strerror( errno ) );
return;
}
size_t textLength = strlen( text );
size_t written = write( fd, text, textLength );
if( written == -1 ) {
printf( "Error writing text: errno: %d - %s\n", errno, strerror( errno ) );
goto closeFile;
}
else if( written < textLength ) {
printf( "Warning: Only %d of %d bytes were written.", written, textLength );
goto closeFile;
}
else {
// Carry on as normal.
}
closeFile:
if( close( fd ) == -1 ) {
printf( "Error closing file: errno: %d - %s\n", errno, strerror( errno ) );
}
}
推荐阅读
- java - logback 不会将异常记录到从 ThreadPoolTaskExecutor 池线程抛出的文件中
- firebase - Firebase FCM 向消息添加分析标签失败
- asp.net - aspx 智能感知不工作。标记推荐变为 <%@ %>。如何解决这个问题?
- memory-management - lex/yacc 如何使用数组访问内存?
- javascript - 如何每月在 Firebase 中制作销售报告?
- .net - 在 binace 上放置未来订单时出现对象引用错误
- python - Pytorch 中的线性回归问题。未实现错误
- python - Python 3 中的模型集合
- flutter - 用于映射键的 Flutter Firestore whereIn 子句
- go - 我们可以在 Go 中将类型断言与接口方法一起使用吗?