I couldnt find specific answer to my question. I am really low level, just started and had a class in which I learned to create file from the CodeBlocks. Took code with me home but it wont work because its not on the same computer. So, the idea was to make something that will allow user to choose path for the newly formed .txt file. When, instead of s, I manually insert "c:\example.txt" or something like that, the code creates a file "example.txt" but when I send it as input it simply wont. Why?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *a=NULL;
char s[50];
puts("Enter the path of the file: ");
fgets(s,50,stdin);
a=fopen(s,"w");
if(a==NULL)
exit(1);
else
printf("Successful input");
}
So the entire problem was the fgets function which adds the \nat the end? Is there any other idea to make this work?
You can replace the
fgets(s,50,stdin);
with
scanf("%49[^\n]%*c", s);
- this reads input excluding the \n into s, as long as its size allows, and consumes the \n, so that it doesn't get into the way of possible later input.
Related
I am a new learner to the C language. I am trying to figure out how to use scanf. This is my code so far.
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?");
scanf(" %c", &lastInitial);
}
When I run this code (I'm using VS Code), it shows that the file is running, but nothing shows up. When I go to the top to click the run button again, it says this code is already running. If I stop the run, delete the scanf line and run again, the file runs and displays "What is your last inital?" I am confused as to why adding scanf to the file stops the printf and doesn't allow any user input.
You might have run into a little intricacy with how printf works. When you run printf("What is your last inital?");, this text does not end with a newline (\n) character. As a result, some environments might not display it right away, delaying it until you printf a complete line or until the program ends. This is done for efficiency, since the internal steps to actually get output to your screen are a bit expensive.
When you remove the scanf, the program ends right after the printf; as the program is ending any text that's still waiting to be displayed gets sent to the screen by the built-in shutdown routines in the C standard library. However, when the scanf is included, the text gets buffered/delayed, and doesn't ever get sent to the screen sine the program is stalled waiting for user input. You can force the output to be sent immediately using a newline:
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?\n");
scanf(" %c", &lastInitial);
}
Or if you don't want a newline, you can tell the C standard library to explicitly send all output text right away:
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?");
fflush(stdout);
scanf(" %c", &lastInitial);
}
When you run the program, you should switch from "OUTPUT" to "TERMINAL".
You need to install the "Code Runner" extension.
Then go to File-->Preferences-->Settings in the search write code runner, and below will appear some settings of code runner, you need to find Run In Terminal, and turn it on.
THAT'S ALL :)
My program is supposed to let the user edit a line of a file. The user edits the line and sends it back by pressing enter. Therefore I would like to print the current line which is about to be edited, but kind of print it on stdin instead of stdout.
The only problem I don't know how to solve is how I can prefill the stdin. I've already tried this:
char cprefill[] = {"You may edit this line"};
char cbuffer[100];
fprintf(stdin, cprefill);
fgets(cbuffer, 100, stdin);
This seems to be the simplest solution, but is probably too simple to work. The fprintf doesn't print anything to stdin. What is the correct way?
Edit:
This is how it is supposed to look like. Please mind the cursor which can be moved.
The C language has no notion of terminal nor of line edition, so it cannot be done in a portable way. You can either rely on a library like [n]curses to get an almost portable solution, or if you only need that on one single OS use low level OS primitives.
For exemple on Windows, you could feed the input buffer by simulating key strokes into the appropriate window (for example by sending WM_CHAR messages) just before reading, but that would be highly non portable - and in the end is no longer a C but a Windows solution...
First you need the libreadline developer package. (You might also need the libreadline if it's not already available on your system)
On Debian / Ubuntu that's apt install libreadline-dev (plus libreadline6 if you need the binaries also - 6 might be different on your platform)
Then you can add an history to readline, like this
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
...
char cprefill[] = {"You may edit this line"};
add_history(cprefill);
char *buf = readline("Line: ");
printf("Edited line is %s\n", buf);
// free the line allocated by readline
free(buf);
User is prompted "Line: ", and has to do UP ARROW to get and edit the history, i.e. the cprefill line.
Note that you have to compile/link with -lreadline
readline prints the prompt given as argument, then waits for user interaction, allowing line edition, and arrows to load lines stored in the history.
The char * returned by readline has then to be freed (since that function allocates a buffer with malloc()).
You could use GNU Readline. It calls the function that rl_startup_hook points to when starting, where we use rl_insert_text to put our text in the line buffer.
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
int prefill(void)
{
rl_insert_text("You may edit this line");
return 0;
}
int main(void)
{
char *cbuffer;
puts("Please edit the following line");
rl_startup_hook = prefill;
if ((cbuffer = readline(NULL)) == NULL) /* if the user sends EOF, readline will return NULL */
return 1;
printf("You entered: %s\n", cbuffer);
free(cbuffer);
return 0;
}
For more information, see the GNU Readline manual.
I am working on a school project in which we have to do some operations (select, min, max) on a table saved in .txt file.
The problem is that we can't use common functions such as fopen, fscanf, fclose.
The program will be launched from command line like this: .\project.exe select parameters <table.txt
Do you have some ideas how to get content of the .txt file to stdin without using fopen?
Thanks.
You do not need to open the file - the operating environment will do it for you.
When your program is called with <table.txt, your standard input is switched to read from that file instead of the keyboard. You can use scanf to read the data, and do not worry about opening and closing the file.
Same goes for the output of your program and the >table_out.txt redirection: rather than printing to the screen, printfs in your program would be writing to a file, which would be automatically closed upon your program's exit. Of course if you need to print something to the screen when your output is redirected, you can do so by printing to stderr (e.g. fprintf(stderr, "Invalid table format\n").
There are few ways to acomplish this.
Reading STDIN
I guess the teacher wants this method in particular. The idea is reading standard input rather than particular file.
In C++ you can simply read the stdin object. Here's an example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[80];
int i;
printf("Enter a string: ");
fgets(str, 10, stdin);
/* remove newline, if present */
i = strlen(str)-1;
if( str[ i ] == '\n')
str[i] = '\0';
printf("This is your string: %s", str);
return 0;
}
Source: http://www.java2s.com/Code/C/Console/Usefgetstoreadstringfromstandardinput.htm
Using system utils
You can call "type" util # Windows (not sure about it) or "cat" util in Linux as a subprocess to read some partticular file. But this is rather a "hack", so I do not recommend using this one.
So im working on learning how to do file I/O, but the book I'm using is terrible at teaching how to receive input from a file. Below is is their example of how to receive input from a file, but it doesn't work. I have copied it word for word, and it should loop through a list of names until it reaches the end of the file( or so they say in the book), but it doesn't. In fact if I leave the while loop in there, it doesn't print anything.
#include <stdio.h>
#include <conio.h>
#define MAX 250
int main()
{
char name[MAX];
FILE*pRead;
pRead=fopen("test.txt", "r");
if (pRead==NULL)
{
printf("file cannot be opened");
}else
printf("contents of test.txt");
while(fgets(name,sizeof(name),pRead)!=NULL){
{
printf("%s\n",name);
fscanf(pRead, "%s", name);
}
getch();
}
Even online, every beginners tutorial I see does some variation of this, but I can't seem to get it to work even a little bit.
I believe your array is too small and therefore when you are reading fscanf overwrites memory causing bizarre behavior
If you just want to read the file - presuming now there is one name per line followed by newline in the input file - just read the file using fgets() instead.
#define MAXLINE 256
char name[MAXLINE];
while (fgets(name,sizeof(name),pRead)!=NULL)
{
// do whatever
}
I am working on TTCN-3 (Testing and Test Control Notation) scripting language. I wanted to prepare on guideline checker for this code files.
For that I want to read lines of TTCN-3 script file( some thing like file.ttcn ) one by one into a buffer. But for me fopen / sopen / open / fgetc / fscanf are not able to work properly and are not reading the file correctly. It is giving NULL. Is there any way I can read characters of it into a buffer. I think C cannot read files with more than three extension characters (like .ttcn). Forgive me if my assumption is wrong.
My Environment is Turbo C on windows.
Edit:
Yes I checked those errors also but they are giving unknown error for read()
and no such file or directory exists.
My code is as follows
#include <errno.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
int main(void)
{
int handle;
int status;
int i=0;
char ch;
FILE *fp;
char *buffer;
char *buf;
clrscr();
handle = sopen("c:\\tc\\bin\\hi.ttcn", O_BINARY, SH_DENYNONE, S_IREAD);
/here even I used O_TEXT and others/
if (!handle)
{
printf("sopen failed\n");
// exit(1);
}
printf("\nObtained string %s #",buf);
close(handle);
fp=fopen("c:\\tc\\bin\\hi.ttcn","r"); \\sorry for the old version of one slash
if(fp==NULL) \\I was doing it with argv[1] for opening
{ \\user given file name
printf("\nCannot open file");
}
ch=fgetc(fp);
i=0;
while(i<10)
{
printf("\ncharacter is %c %d",ch,ch);
i++; //Here I wanted to take characters into
ch=fgetc(fp); //buffer
}
getch();
return 0;
}
The most likely culprit is your Turbo C, an ancient compiler. It's techincally a DOS compiler, not Windows. That would limit it's RunTme Library to 8.3 filenames. Upgrade to something newer - Turbo C++ seems like a logical successor, but Microsoft's VC++ Express would work as well.
Your assumption is wrong about extensions. If fopen is returning NULL, you should output the result of strerror(errno) or use the perror() function to see why it failed.
Edit: The problem is probably because you have "c:\tc\bin\hi.ttcn". in C, "\t" is interpreted as tab, for example.
You could do
"c:\\tc\\bin\\hi.ttcn"
But this is extremely ugly, and your system should accept:
"c:/tc/bin/hi.ttcn"
MS-DOS does not know about long file names, thos including files with extensions longer than 3 characters. Therefore, the CRT provided by Turbo C most probably does not look for the name you are providing, but a truncated one - or something else.
Windows conveniently provides a short (i.e. matching the 8.3 format, most of the time ending in ~1 unless you play with files having the same 8-character prefix) file name for those; one way to discover it is to open a console window and to run "dir /x" in the folder your file is stored.
Find the short name associated to your file and patch it into your C source file.
Edit: Darn, I'll read the comments next time. All credits to j_random_hacker.
Now that you've posted the code, another problem comes to light.
The following line:
fp=fopen("c:\tc\bin\hi.ttcn","r");
Should instead read:
fp=fopen("c:\\tc\\bin\\hi.ttcn","r");
In C strings, the backslash (\) is an escape character that is used to encode special characters (e.g. \n represents a newline character, \t a tab character). To actually use a literal backslash, you need to double it. As it stands, the compiler is actually trying to open a file named "C:<tab>c<backspace>in\hi.ttcn" -- needless to say, no such file exists!