[英]C using open()read()write() to access text modify it and store in a new file
My program is supposed to take text from a file given in the command line change it to uppercase and store it in another file. 我的程序应该从命令行中给出的文件中获取文本,将其更改为大写并将其存储在另一个文件中。 It works except the output file has a whole bunch of garbage after the converted text. 它的工作原理除了输出文件在转换后的文本后有一大堆垃圾。 Thank you Edit: I changed my read to check for 0 bytes and used ret_in to write per Pyjamas it still pulls two or three garbage values. 谢谢编辑:我更改了我的读取以检查0字节并使用ret_in来编写每个睡衣它仍然会拉出两个或三个垃圾值。 It's definitely read getting the garbage because when I output the buffer before converting it's there. 这肯定是读取垃圾,因为当我在转换它之前输出缓冲区时。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUF_SIZE 500
int main(int argc, char* argv[]){
char buffer[BUF_SIZE];
int ret_in;
char inputf[100],outputf[100],txt[4],up[3];
// Takes input and adjusts it to the correct file type.
strcpy(inputf,argv[1]);
strcpy(outputf,argv[1]);
strcat(outputf,".up");
printf("%s\n",outputf);
strcat(inputf,".txt");
printf("%s\n",inputf);
int output, input,wrt;
int total;
//opens input file
input=open(inputf, O_RDONLY);
if (input == -1) {
printf("Failed to open file\n");
exit(1);
}
ret_in = read(input,buffer,BUF_SIZE);
total = ret_in;
// output to console
while (ret_in!= 0) {
// printf("%s\n", buffer);
ret_in = read(input,buffer,BUF_SIZE);
total += ret_in;
}
//ret_in= read(input,&buffer,BUF_SIZE);
puts(buffer);
close(input);
int i = 0;
while(buffer[i]) {
buffer[i] = toupper(buffer[i]);
i++;
}
// output buffer in console
puts(buffer);
//output filename in console
printf("%s\n",outputf);
// Opens or creates output file with permissions.
output = open(outputf, O_CREAT| S_IRUSR | O_RDWR);
if (output == -1) {
printf("Failed to open or create the file\n");
exit(1);
}
// write to output file
wrt = write(output, buffer,total);
close(output);
return 0;
}
Because you read ret_in
bytes from file, but you write BUF_SIZE
to the file, you should write ret_in
bytes to the file. 因为您从文件读取ret_in
字节,但是您将BUF_SIZE
写入文件,您应该将ret_in
字节写入该文件。 You are not supposed to read BUF_SIZE
bytes from file every time, it depends, right? 你不应该每次都从文件中读取BUF_SIZE
字节,这取决于,对吗?
write(output, buffer,BUF_SIZE);//wrong
write(output, buffer,ret_in); //right
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.