gpt4 book ai didi

c - 从键盘读取文件名

转载 作者:行者123 更新时间:2023-11-30 20:35:14 25 4
gpt4 key购买 nike

基本上,在下面的代码中,我尝试从键盘读取文件名(即 input.txt 和 output.txt),但出现“段错误”。该程序还将小写字母转换为大写字母,并将大写字母转换为小写字母。有什么建议么?我究竟做错了什么?

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{

char c;
int charToLowerCase = 0;
int charToUpperCase = 0;
int countCharacters = 0;
FILE *in_file = NULL;
FILE *out_file = NULL;
char str_in[100];
char str_out[100];
char *s_in = NULL;
char *s_out = NULL;

gets(str_in);
gets(str_out);

if (s_in != NULL)
in_file = fopen(str_in, "r");

if (s_out != NULL)
out_file = fopen(str_out, "w");

c = fgetc(in_file);
while (c != EOF)
{
if (c >= 'A' && c <= 'Z')
{
fprintf(out_file, "%c", tolower(c));
charToLowerCase++;
}
else if (c >= 'a' && c <= 'z')
{
fprintf(out_file, "%c", toupper(c));
charToUpperCase++;
}
else
fprintf(out_file, "%c", c);

c = fgetc(in_file);
countCharacters++;
}
fprintf(out_file, "\n");
fprintf(out_file, "Read %d characters in total, %d converted to upper-case, %d to lower-case.\n", countCharacters, charToUpperCase, charToLowerCase);

fclose(in_file);
fclose(out_file);
return 0;
}

最佳答案

你想要这个:

int main() 
{
int c; //<<< int instead of char
int charToLowerCase = 0;
int charToUpperCase = 0;
int countCharacters = 0;
FILE *in_file = NULL;
FILE *out_file = NULL;
char str_in[100];
char str_out[100];

gets(str_in);
gets(str_out);

in_file = fopen(str_in, "r");
if (in_file == NULL)
{
// file could not be opened
printf ("Could not open file %s\n", str_in);
return 1;
}

out_file = fopen(str_out, "w");
if (in_file == NULL)
{
// file could not be opened
printf ("Could not open file %s\n", str_out);
return 1;
}

...

关于c - 从键盘读取文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39973856/

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