简体   繁体   English

字符数组在文件处理中不起作用

[英]The character array doesn't work in file handling

What i was trying to do is, create a program that asks the user to enter how much long text he want to write. 我正在尝试做的是,创建一个程序,要求用户输入他要写多长时间的文本。 And after than whatever he writes in the console gets automatically saved in a textfile named file at following path mentioned in the code. 然后,他在控制台中编写的任何内容都会自动保存在代码中提到的以下路径的名为file的文本file中。 So, to ask user the size of character array i used int i . 因此,要问用户我使用int i的字符数组的大小。 And then used gets command to pick up whatever he wrote as it is with spaces and other characters. 然后使用gets命令拿起他用空格和其他字符写的任何内容。 But the code doesn't seem to work it asks the user about how many character and then runs complete and terminates. 但是该代码似乎不起作用,它询问用户多少字符,然后运行完成并终止。 Also tell me what should do to make it create a new file in Data folder everytime user starts the program? 还告诉我每次用户启动程序时应如何做才能在Data文件夹中创建一个新文件? I don't want to overwrite the existing file or append text to it. 我不想覆盖现有文件或向其添加文本。 I want to create a new file and let the user name it whatever he feels like and then store that text in that new file. 我想创建一个新文件,并让用户以自己喜欢的方式对其进行命名,然后将该文本存储在该新文件中。

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

int main()
{
FILE *file = fopen("C://Users//Abhimanyu Aryan//Desktop//Data//Hello.txt", "w");

printf("\t\tThis program allows you to write detailed data\n\n\n");

int c;
printf("you many characters file you want to write? Specify: ");
scanf("%i",&c);

printf("\n\nEnter your text here: ");

char text[c];

gets(text);


fprintf(file, "%s" , text);

printf(" the file has been written succesfully!!!!");

fclose(file);

return 0;

}

There are a couple of things wrong with your code. 您的代码有几处错误。 First, you should check the return value from fopen() to make sure everything was successful: 首先,您应该检查fopen()的返回值以确保一切成功:

FILE *file = fopen("C://Users//Abhimanyu Aryan//Desktop//Data//Hello.txt", "w");
if (file == NULL) {
    /* Handle fopen() error */
    fprintf(stderr, "Couldn't open file for writing!");
    exit(EXIT_FAILURE);
}

The second mistake is that you are using gets() . 第二个错误是您正在使用gets() gets() is old, deprecated and unsafe, you should never use it . gets() 是旧的,不建议使用的并且不安全,永远不要使用它 Use fgets() instead: 使用fgets()代替:

char text[c];

fgets(text, sizeof text, stdin);

If you want the user to choose the filename, it's a matter of asking him first, and then open the specified filename for writing. 如果要用户选择文件名,则可以先询问他,然后打开指定的文件名进行写入。 If the file doesn't exist, it will automatically be created: 如果文件不存在,将自动创建:

#define MAX_FILENAME_LENGTH 128

char filename[MAX_FILENAME_LENGTH];
printf("Enter filename (max. %zu characters): ", sizeof(filename)-1);
fgets(filename, sizeof filename, stdin);

FILE *file = fopen(filename, "w");
if (file == NULL) {
    /* Handle fopen() error as mentioned above*/
}

UPDATE : 更新

Note that scanf("%i", &c); 注意scanf("%i", &c); will leave a newline on the buffer (from when you press the ENTER key). 将在缓冲区上保留换行符(从您按ENTER键时开始)。 That's why fgets() is returning prematurely without waiting: it reads a newline left on the buffer from the previous input and assumes you're done ( fgets stops when it hits a newline). 这就是fgets()过早返回而无需等待的原因:它从先前的输入中读取缓冲区中剩余的换行符,并假定您已完成操作( fgets碰到换行符时会停止)。 To fix it, you have to consume the buffered newline before calling scanf() . 要修复它,您必须在调用scanf()之前使用缓冲的换行符。 You can do so with getchar() , for example: 您可以使用getchar() ,例如:

/* ... */
scanf("%i",&c);
/* Consume newline left on buffer from scanf */
if (getchar() == '\r')
    (void) getchar();
printf("\n\nEnter your text here: ");
/* ... */

The if (gethcar() == '\\r') is there to make the code work in the case that stdin was redirected to a file with DOS end-of-lines ( \\r\\n rather than only \\n ), in which case 2 characters must be consumed. if (gethcar() == '\\r')stdin重定向到带有DOS行尾( \\r\\n而不是仅\\n )的文件的情况下,可以使代码工作在这种情况下,必须使用2个字符。 Even if you plan to use this from the terminal only (without stdin redirecton), I would still recommend leaving it that way - pressing ENTER might push \\r\\n to stdin too. 即使您打算仅在终端上使用此功能(不带stdin redirecton),我仍然建议您采用这种方式-按ENTER键也可以将\\r\\n推入stdin

I would change 我会改变

FILE *file = fopen("C://Users//Abhimanyu Aryan//Desktop//Data//Hello.txt", "w");

to

FILE *file = fopen("C:/Users/Abhimanyu Aryan/Desktop/Data/Hello.txt", "w");

or 要么

FILE *file = fopen("C:\\Users\\Abhimanyu Aryan\\Desktop\\Data\\Hello.txt", "w");

I don't know that having two forward slashes as directory separator causes any problems but it is certainly not necessary. 我不知道使用两个正斜杠作为目录分隔符会导致任何问题,但绝对没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM