I'm printing this:
char aulaIP2[50];
char aula[50];
printf("Enter the name of classroom: ");
fgets(aula, 49, stdin);
if (fgets(aula, sizeof aula, stdin)){
printf("Enter IP classroom: ");
fgets(aulaIP2, 49, stdin);
FILE *file = fopen("aules.text", "w+");
fprintf(file, "%s:%s", aula, aulaIP2);
fclose(file);
getchar();
}
and the output in the file is:
306
:127
and I want:
306:127
Why isn't fprintf able to print that in the same line? I have already tried doing it with two fprintfs but it's the same result.
From fgets documentation:
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
So when you read in your strings, they actually contain the newline character, which is then printed as part of the string. Instead of using fgets() use scanf() which will read until the first whitespace (and not including):
scanf( "%50s", aula );
According to http://www.cplusplus.com/reference/cstdio/fprintf/ fprintf is able to print in one line. See the example on the bottom of that page.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
char* aula = "306";
char* aulaIP2 = "127";
FILE* file = fopen("aules.text", "ab+");
fprintf(file, "%s:%s", aula, aulaIP2);
fclose(file);
return 0;
}
When I read aules.text, I see:
306:127
Are aula and aulaIP2 actually strings, or were you trying to write integers instead (%d)?
Related
I am writing a basic program to copy text to another text file. But in the console window after entering the filename from where text should be taken, the program ends and does not go further. How can I solve this problem?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char filename1, filename2;
FILE *infile;
FILE *outfile;
printf("Enter a data file name:");
scanf("%s", filename1);
infile = fopen("filename1", "r");
printf("Enter a input file name:");
scanf("%s", filename2);
outfile = fopen("filename2", "w");
if (infile == NULL || outfile == NULL) {
printf("Problem in opening files");
exit(0);
}
printf("files opened successfully");
char characters;
do {
characters = getc(infile);
fprintf(outfile,"%s", characters);
printf("%s", characters);
} while (!feof(infile));
fclose(infile);
fclose(outfile);
return 0;
}
There are a few problems with your program:
You are using char variables to hold names of files. These variables should be char arrays or pointers to the first char of some allocated memory.
fopen("filename2", "w") seems wrong. Although, the first argument should be a char *, you are not reading / writing the files you just asked the user to enter.
fprintf(outfile,"%s",characters) - You are using %s to print characters. This will invoke UB.
char characters - The last character of a file, the EOF character is guaranteed to fit in an int. The characters variable should be declared as an int so that it can hold the EOF character.
Here is the program that works:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char filename1[10], filename2[10];
FILE *infile;
FILE *outfile;
printf("Enter a data file name:");
scanf("%s",filename1);
infile = fopen(filename1, "r");
printf("Enter a input file name:");
scanf("%s",filename2);
outfile = fopen(filename2, "w");
if (infile==NULL || outfile==NULL) {
printf("Problem in opening files");
exit(0);
}
printf("files opened successfully");
int characters;
/*do {
characters=getc(infile);
fprintf(outfile,"%s",characters);
printf("%s",characters);
} while(!feof(infile));
*/
while ((characters = getc(infile)) != EOF) {
fprintf(outfile, "%c", characters);
printf("%c", characters);
}
fclose(infile);
fclose(outfile);
return 0;
}
There are a number of issues.
char filename1, filename2;
This only allows filename1 and filename2 to hold a single char - not a C string. You need to reserve memory as a char array. Like:
char filename1[64], filename2[64]; // Allow 63 chars for file name
Then
scanf("%s",filename1);
is really bad as it allows the user to overflow your input buffers. Consider using fgets or at least do:
scanf("%63s",filename1); // Limit user input to 63 chars as the buffer is 64
// The "last" char is for the string termination
Then the loop:
First, characters shall be int so that you can check for EOF. Further, check directly on getc instead of using feof. And don't use %s for printing a single char to the output file - use %c. Like
int characters;
while(1) {
characters=getc(infile);
if (characters == EOF) break; // Break (aka jump out of the loop) on
// end-of-file or errors
fprintf(outfile,"%c",characters); // %c instead of %s
// or use: putc(characters, outfile)
// instead of fprintf
printf("%s",characters);
}
First of all I am new to files in c, so it may be a simple question,
however I still didn't find a solution:
let's say that's the content of my file:
99
blah blah
...
...
I want to scan only the number from the beginning (it is always in a separate line)
My question is how to make it take the number (99) as one number and stop scanning.
int main(){
FILE* fp = fopen(file_name, "r");
int integer;
...
fclose(fp);
printf("%d", integer);
}
output for the file example:
99
-the nuber can be between 1 and 100-
I want to scan only the number from the beginning (it is always in a separate line).
That's a good hint, suggesting a line by line parsing of the input. You can use a combination of fgets(1) and sscan(2) to read that number.
fgets will read up to a certain number of character from a stream and store those character into a buffer. If it finds a newline, it stops reading, store the newline into the buffer followed by the null-terminator. Otherwise it only adds the terminator. If it fails, it returs a NULL pointer.
sscanf works basically like scanf or fscanf, but it reads from a character array, not from a stream.
It's also better to always check the return value of those library function.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 1024
int main(void)
{
char const *file_name = "data.txt";
FILE *in_file = fopen(file_name, "r");
if (!in_file) {
fprintf(stderr, "Error while reading \"%s\": %s", file_name, strerror(errno));
return EXIT_FAILURE;
}
char buffer[BUF_SIZE];
int number = 0;
while( fgets(buffer, BUF_SIZE, in_file) ) {
if ( sscanf(buffer, "%d", &number) == 1 ) {
if ( 0 < number && number < 100 ) {
printf("%d", number);
break;
}
}
}
fclose(in_file);
return EXIT_SUCCESS;
}
Example.
Some references of the functions used in the previous snippet
1) fgets: man-pages or cppreference.
2) sscanf: man-pages or cppreference
Why not use scanf? (fscanf to be more precise):
On success, the function returns the number of items of the argument
list successfully filled.
(source: cppreference)
So just check how many values did you read, if 0 that means it's not a number so you can just skip that string, for that you can use "%*" prefix to ignore the data.
You also said:
I want to scan only the number from the beginning (it is always in a
separate line)
so after you read the number just skip the whole line with "%*[^\n]" (reads
data until a new line symbol is encountered)
int num;
int scanReturn;
FILE* f = fopen("file.txt", "r");
...
do {
scanReturn = fscanf(f, "%d", &num);
if(scanReturn == 0)
{
scanReturn = fscanf(f, "%*s");
}
else if(scanReturn != EOF)
{
fscanf(f, "%*[^\n]");
printf("%d, ", num);
}
} while(scanReturn != EOF);
fclose(f);
This is the C code I have so far. I am reading the first name and last name from the input file but the thing that is giving me trouble is to print out the other stuff.
I have to take a line like this:
Venus Jensen 33770530841 vbjensen#oqtu.edu FRNO 624-771-4676 SIJ SBE WHV TVW
and remove the extra stuff to make it like this:
vbjensen Venus Jensen (624)771-4676
My problem is that I am getting the right output but for some of the lines that(1) don't have the FRNO or something equivalent and (2) not having the # symbol, the line still shows up. For example, the lines:
Noe Richard 974927158 nirichar#bvu.edu 079-651-3667 HAVQ
Phillip Sandoval 836145561 pusandov#luu.edu OXRU 697-728-1807 LHPN GUX
These lines should not be printed since the first one does not have the FRNO equivalent and the second one does not have the # symbol. Every time I try to add the format operation to match but not save, the program sscanf function starts to mess up.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main()
{
// Open the input file and print an error message if we're unsuccessful.
// (the error message is mostly to help you with debugging. We won't test
// this behavior).
FILE *fp = fopen("input.txt", "r");
char line[500];
if(!fp) {
printf("Can't open input file\n");
exit(1);
}
// Counting input lines, so we can report errors.
// Keep reading input lines until we reach the end-of-file.
// Write an output line or an error message for each one.
do {
int lineCount = 1;
char fName[12];
char lName[12];
//char skipNum[12];
char email[9];
//char firstNum[4];
//char secondNum[4];
//char thirdNum[5];
//printf("%c", ch);
char phone[] = "(123)123-1234";
//fscanf(fp, "%s", fName);
//fscanf(fp, "%s", lName);
//fscanf(fp, "%[1-9]", skipNum);
//fscanf(fp, "%[a-z]", email);
sscanf (line, "%11s%11s%*[ 0-9]%9[^#]%*[^0-9]%3c-%3c-%4c", lName, fName, email, &phone[1], &phone[5], &phone[9]);
//printf("Invalid line");
//printf("\n");
// exit(1);
printf("%s", line);
printf("\n");
printf("%s", email);
printf("%s", fName);
printf("%s", lName);
//printf("%s", skipNum);
//printf("%s", firstNum);
printf("%s", phone);
printf("\n");
lineCount++;
}
while (fgets(line, sizeof line, fp));
return EXIT_SUCCESS;
}
In the format string "%20s%20s%*[ 0-9]%20[^#]#%*s%20s %3c-%3c-%4c"
%20s will scan up to 20 non-whitespace characters. Ignoring leading whitespace and stopping at trailing whitespace.
%*[ 0-9] will scan spaces and digits. The asterisk, *, tells sscanf to discard the scanned characters.
%20[^#]# will scan up to 20 characters or will stop scanning at a #. Then it will try to scan a #. If the # is missing the scan will terminate early.
%*s will scan non-whitespace and discard the characters.
%20s will scan up to 20 non-whitespace characters.
%3c will ignore any leading whitespace and scan three characters.
-%3c will scan a - and then three characters. If the - is missing the scan will terminate early.
-%4c will scan a - and then four characters. If the - is missing the scan will terminate early.
If sscanf does not scan seven items, nothing will be printed.
#include <stdio.h>
#include <stdlib.h>
int main ( void) {
char line[500] = "";
int lineCount = 0;
FILE *fp = NULL;
if ( NULL == ( fp = fopen("input.txt", "r"))) {
fprintf( stderr, "Can't open input file\n");
exit(1);
}
while ( fgets ( line, sizeof line, fp)) {//read each line from the file
char fName[21];
char lName[21];
char match[21];
char email[21];
char phone[] = "(123)567-9012";
lineCount++;
if ( 7 == sscanf ( line, "%20s%20s%*[ 0-9]%20[^#]#%*s%20s %3c-%3c-%4c"
, lName, fName, email, match, &phone[1], &phone[5], &phone[9])) {
printf ( "line [%d] %s %s %s %s\n", lineCount, email, fName, lName, phone);
}
}
fclose ( fp);
return 0;
}
I have the code which must get the double number from the file:
#include <stdio.h>
#include <string.h>
FILE *fr;
int main(void)
{
int n;
double elapsed_seconds;
char line[80];
fr = fopen ("time1.log", "rt");
sscanf (line, "%3.6f", &elapsed_seconds);
printf ("%3.6f\n", elapsed_seconds);
fclose(fr);
}
Now, time1.log contains only number 0.145213. But the program prints 0. Where is the problem?
the posted code is missing a critical line:
Not only does the code need to open the file, it also needs to read the file into the line variable.
Either insert, just after the call to fopen()
fgets( line, sizeof(line), fr );
or (less desirable) replace the call to sscanf() with
fscanf(fr, "%lf", &elapsed_seconds);
Note: if your keep the call to sscanf() then the format string should be: "%lf", the same as for the call to fscanf()
using the call to fscanf() would allow the elimination of the line[] array.
The variable n is never used, so should be eliminated
It should be
#include <stdio.h>
#include <string.h>
FILE *fr;
int main(void)
{
int n;
double elapsed_seconds;
char line[80];
fr = fopen ("time1.log", "rt");
fgets(line, 80, fr); // <--- Note this line
sscanf (line, " %lf", &elapsed_seconds);
printf ("%3.6f\n", elapsed_seconds);
fclose(fr);
}
This is because you have to read the data from the file to the string before sscanfing that string.
Before calling sscanf to parse the data, you need to read the data from the file - call fgets(line,80,fr).
I'm trying to write a program that reads a certain amount of characters from a file name given from command line. Here is what I have:
#include <stdio.h>
int main(int argc, char **argv)
{
int i = 0;
FILE *f;
char* fileName = argv[1];
char buf[40];
f = fopen(fileName, "r");
while(!feof(f)){
fgets(buf, 10, f);
printf("%s\n", buf);
}
fclose(f);
return 1;
}
Say in this particular case I need first 10 chars, then the next 10 chars, etc until the file is over. However, when I run this code it doesn't actually give me the right output. I tried 11 as well since the documentation said fgets() reads n-1 characters, but that doesn't work either. Some stuff at the beginning is read, but nothing afterwards is and it just gives me a bunch of blanks. Any idea what is wrong?
Thanks
The function you are looking for is fread, like this:
fread(buf, 10, 1, f);
It works almost ok if you remove the \n from your printf format string (assuming that you want to basically echo a whole file as is).
I would also loop based on fgets(...) != NULL since feof() will return a true value after fgets errors and hits EOF, so your last buffer-full will be printed twice. You could make a small change to your code as so:
#include <stdio.h>
int main(int argc, char **argv)
{
int i = 0;
FILE *f;
char* fileName = argv[1];
char buf[40];
f = fopen(fileName, "r");
while(fgets(buf, 10, f))
printf("%s", buf);
fclose(f);
return 0;
}
Also, as others have stated, while I took too long to answer, fread may be a better alternative since fgets won't necessarily read 10 chars; it'll stop at every newline and you don't care about reading a line at a time.
fgets is intended to read a line, up to a maximum length. If you want to read 10 characters at a time, regardless of line breaks, you probably want to use fread instead:
Either way, you definitely do not want to use while (!feof(f)). You probably want something like:
int main(int argc, char **argv) {
char buf[40];
FILE *f;
if (NULL == (f=fopen(argv[1], "r"))) {
fprintf(stderr, "Unable to open file\n");
return EXIT_FAILURE;
}
size_t len;
while (0 < (len=fread(buf, 10, 1, f)))
printf("%*.*s\n", len, len, buf);
return 0;
}